[英]How to add NSLayoutConstraint to subview of programmatically created NSView subclass?
在這里,我以編程方式創建一個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
}
}
在上面的子類中, NSTextField
的約束在初始化時被設置為常量。 我想添加NSLayoutConstraint
而不是在初始化時添加框架。
在什么方法,我應該補充NSLayoutConstraint
為NSTextField
到DialogView
本身。
您可以將它們添加到updateConstraints
,並使用布爾值確保它們只設置一次:
override func updateConstraints() {
super.updateConstraints()
guard !constraintsSet else{
return
}
constraintsSet = true
...<Add here>
}
此外,您應該將translatesAutoresizingMaskIntoConstraints
設置為 false 對於您使用約束定位的任何子視圖:
textLabel.translatesAutoresizingMaskIntoConstraints = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.