[英]How to add NSLayoutConstraint to subview of programmatically created NSView subclass?
Here I am creating a NSView
subclass programmatically and add it to NSViewController
view.在这里,我以编程方式创建一个NSView
子类并将其添加到NSViewController
视图中。
class DialogView: NSView {
var value: Int = 0
let textLabel: NSTextField
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
init(position: CGPoint, width: CGFloat, height: CGFloat value: Int) {
textLabel = NSTextField.init(frame: NSRect(x: width/5.0, y: height/5.0, width: width/1.5, height: height/5.0))
textLabel.alignment = NSTextAlignment.center
super.init(frame: NSRect(x: position.x, y: position.y, width: width, height: height))
addSubview(textLabel)
self.value = value
textLabel.stringValue = "\(value)"
textLabel.textColor = NSColor.lightGray
}
}
As in above subclass, the constraint for NSTextField
is being set constant at init.在上面的子类中, NSTextField
的约束在初始化时被设置为常量。 Instead of adding frame at initializing, I would like to add NSLayoutConstraint
.我想添加NSLayoutConstraint
而不是在初始化时添加框架。
In what method should I add NSLayoutConstraint
for NSTextField
to DialogView
itself.在什么方法,我应该补充NSLayoutConstraint
为NSTextField
到DialogView
本身。
You can add them in updateConstraints
, with a boolean to make sure they are only set once:您可以将它们添加到updateConstraints
,并使用布尔值确保它们只设置一次:
override func updateConstraints() {
super.updateConstraints()
guard !constraintsSet else{
return
}
constraintsSet = true
...<Add here>
}
Also you should set translatesAutoresizingMaskIntoConstraints
to false for any subviews you are positioning with constraints:此外,您应该将translatesAutoresizingMaskIntoConstraints
设置为 false 对于您使用约束定位的任何子视图:
textLabel.translatesAutoresizingMaskIntoConstraints = false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.