简体   繁体   中英

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.

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. Instead of adding frame at initializing, I would like to add NSLayoutConstraint .

In what method should I add NSLayoutConstraint for NSTextField to DialogView itself.

You can add them in updateConstraints , with a boolean to make sure they are only set once:

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:

textLabel.translatesAutoresizingMaskIntoConstraints = false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM