gpt4 book ai didi

objective-c - 如何将 NSLayoutConstraint 添加到以编程方式创建的 NSView 子类的 subview 中?

转载 作者:行者123 更新时间:2023-11-30 13:06:53 24 4
gpt4 key购买 nike

在这里,我以编程方式创建一个 NSView 子类并将其添加到 NSViewController View 中。

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 的约束在 init 时设置为常量。我想添加 NSLayoutConstraint,而不是在初始化时添加框架。

我应该通过什么方法将 NSTextFieldNSLayoutConstraint 添加到 DialogView 本身。

最佳答案

您可以将它们添加到 updateConstraints 中,并使用 bool 值来确保它们仅设置一次:

override func updateConstraints() {
super.updateConstraints()
guard !constraintsSet else{
return
}
constraintsSet = true
...<Add here>
}

此外,对于您使用约束定位的任何 subview ,您应该将 translatesAutoresizingMaskIntoConstraints 设置为 false:

textLabel.translatesAutoresizingMaskIntoConstraints = false

关于objective-c - 如何将 NSLayoutConstraint 添加到以编程方式创建的 NSView 子类的 subview 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com