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

标签 objective-c swift macos cocoa

在这里,我以编程方式创建一个 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/

相关文章:

python - Python 的 Mechanize 中的 BeautifulSoup 错误

macos - 寻找 。并替换为 . & 新队 & ;在 OSX 中(对于新手来说)

objective-c - ARKit – 空间音频几乎不会随距离改变音量

swift - 如何杀死系统扩展或网络扩展?

xcode - 在快速附加到电子邮件之前压缩视频大小

swift - 以编程方式固定宽度,动态高度 UILabel?

c++ - 在 65536 位置访问迭代器的指针运算符导致段错误

iphone - CFStream SSL 错误 -9800

ios - 自定义构建条件和警告 Xcode

iphone - 在 ios wifi 网络上查找对等点