【发布时间】:2019-07-28 09:30:13
【问题描述】:
在 MacOS 项目上。
我正在尝试在文本字段下画一条线(通过使文本字段透明,我可以创建一个“请填写空白”样式的视图,要求用户输入数据)。我创建了一个名为lineDrawer 的简单NSView 子类,只是为了画线,然后我尝试将lineDrawer 的一个实例作为子视图添加到我让用户输入他的姓名的视图中。该线应绘制在透明文本字段的正下方。文本字段是视图的 IBOutlet 并且已经在正确的位置,我希望该行与文本字段具有完全相同的框架,因此如果我从lineDrawer's (minX, minY) 到(maxX, minY) 绘制路径,则路径正好在透明文本字段的下方。
我不能让它工作,因为我设置后
lineView.translatesAutoresizingMaskIntoConstraints = false
并添加了我自己的约束,自定义视图不会绘制。我认为这与我没有为程序提供足够的信息有关究竟在何处绘制视图有关,但我无法弄清楚这里缺少什么。顺便说一句,如果我不设置约束,它只会在其框架的位置绘制视图。如果我设置约束,则什么都不会显示。
NickName: NSViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
greetingLine.font = .labelFont(ofSize: 50)
nameField.font = .labelFont(ofSize: 50)
nameField.isBezeled = false
let lineView = lineDrawer.init()
lineView.setFrameSize(nameField.frame.size)
self.view.addSubview(lineView)
lineView.translatesAutoresizingMaskIntoConstraints = false
let lineConstraintX = NSLayoutConstraint.init(item: lineView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let lineConstraintY = NSLayoutConstraint.init(item: lineView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.3, constant: 0)
self.view.addConstraints([lineConstraintY, lineConstraintX])
}
@IBOutlet weak var nameField: NSTextField!
@IBOutlet weak var greetingLine: NSTextField!
还有lineDrawer: NSView:
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
let context = NSGraphicsContext.current?.cgContext
context!.beginPath()
context!.move(to: CGPoint(x: self.bounds.minX, y: self.bounds.minY))
let endPoint = CGPoint.init(x: self.bounds.maxX, y: self.bounds.minY)
context!.addLine(to: endPoint)
context!.move(to: CGPoint(x: 0, y: 0))
context!.addLine(to: CGPoint(x: 10, y: 10))
let loadedColor = ColorGetter.getCurrentThemeColor()
context!.setStrokeColor(loadedColor.cgColor)
context!.setLineWidth(5)
context!.strokePath()
print("drawing")
}
非常感谢任何愿意为此提供帮助的人!
【问题讨论】:
标签: swift macos cocoa autolayout custom-view