macosswiftnstoolbarnstoolbaritem

NSToolbarItem stretch to minimum width


I've added a NSToolbar to my window and inserted some items. Two of them contain a custom view (NSTextFiled as a label and a NSButton). I've set a maximum and minimum width for both these items and they display fine but they are much larger than needed making the label and especially the button annoyingly big with undesired space.

Button too big

I'm looking for a way to set the width of button and its item to the minimum required by the text it contains.


Solution

  • After playing around I've added an outlet also for the NSToolbarItem and used the following function to change the text:

    @IBOutlet weak var manageSessionItem: NSToolbarItem!
    @IBOutlet weak var manageSession: NSButton!
    
    func setManageSessionTitle(title: String) {
        let s: NSString = title
        let attr=[NSFontAttributeName: manageSession.font!]
        //Add width to compensate for button graphics
        let w=s.sizeWithAttributes(attr).width + 20
    
        manageSession.frame.size.width = w
        manageSessionItem.minSize.width = w
        manageSessionItem.maxSize.width = w
    
        manageSession.title = title
    }