Marco Boschi Marco Boschi - 2 years ago 274
Swift Question

NSToolbarItem stretch to minimum width

I've added a

to my window and inserted some items. Two of them contain a custom view (
as a label and a
). 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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download