swiftnspopupbuttonnscontrol

NSPopUpButton Size Issue: Width is larger than what imposed by constraints


I have a problem with a subclassed NSPopUpButton in OSX. Subclassing is nothing special, just draws the string and image based on the font chosen.

The problem is that when I add the NSButton to a view and, using layout constraints, set its width to a fixed CGFloat value, the button is always larger than the constraint and its leading anchor is also in the wrong place (i.e. to the left of the leading anchor I set originally).

For example, if I add a button to a view in a window (say a rectangular container) and pin its leading anchor to the container leading anchor and give it a width of 80px, the button then appears with its left side 3px to the left of the container leading anchor and its width is 87px, not 80.

The 3 and 7 px difference is always the same, regardless of which width I give the button.

I have also checked in draw(rect) and the received rect is actually 7px wider than the constant I imposed with the constraints.

Can someone help, there must be some sort of embedded OSX process that changes the width of the NSControl).

As I use the same subclass (with the necessary minor modifications) in iOS as well, the problem does not appear and the button is correctly sized.


Solution

  • Printing NSPopUpButton().alignmentRectInsets produces

    NSEdgeInsets(top: 1.0, left: 3.0, bottom: 4.0, right: 4.0)
    

    This is why the layout anchors are all a bit off. They have been moved by some non-zero amount.

    If you don't want that, override alignmentRectInsets to return 0:

    override var alignmentRectInsets: NSEdgeInsets {
        NSEdgeInsetsZero
    }