NSTextField created from custom class appears randomly

68 views Asked by At

I have a main NSView with 2 NSView subviews containing each a custom NSButton (all created in Interface Builder). My custom button class is programmatically creating an NSTextField below the buttons, by adding it from the superview: enter image description here

And the custom NSButton class code:

class buttonUpDown: NSButton {
    var myLabel:NSTextField!
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        let labelWidth=CGFloat(90)

        print("init")
        superview?.autoresizesSubviews = false
        myLabel = NSTextField(frame: NSMakeRect(frame.origin.x+frame.size.width/2-labelWidth/2,frame.origin.y-20,labelWidth,16))
        
        myLabel?.stringValue = "Mesh Quality"
        myLabel.alignment = .center
        myLabel.font? = .systemFont(ofSize: 8)

        myLabel.backgroundColor = .red
        myLabel.isBordered = false
        myLabel.isEditable = false

        superview!.addSubview(myLabel)
    }
}

When I have a single Button referencing the class, the label appears properly. enter image description here

But when I have 2, only 1 label is appearing randomly left or right: enter image description here

What do I miss to have a text displayed below each button ?

1

There are 1 answers

1
Laurent Crivello On

Found the issue. Creating a label in the init function will give erratic positioning of the view frame. Adding them from the draw func, makes it more reliable.