Search code examples
macosswiftwidthnsbutton

NSButton change width


I have a button with a title and image. The title of the button change dependent on the selected language. So i want that the button has always the width of the title plus image. I thought it was something easy like this:

var size = selectMenuItemButton.attributedTitle.size
myButton.bounds.size.width = size.width + 10.0

But the width of the button stay the same. What i'm doing wrong?

Edit: Also try

myButton.frame.size.width = size.width + 10.0

And

myButton.sizeToFit()

Didn't work neither

Edit2: I have created a clear project with two buttons. If the one button is clicked the title of the another button is changed. The outcome is the same, i want that the width is change too, but i can't achieve that

@IBAction func buttonClicked(sender: AnyObject) {
    println(test.attributedTitle.size.width)
    myButton.title = "blublublublub"
    var size = test.attributedTitle.size
    myButton.frame.size.width = size.width
    println(test.attributedTitle.size.width)
}

Solution

  • I think i have the answer, i needed just set title again after i set the size:

    myButton.title = "blublublublub"
    var size = myButton.attributedTitle.size
    myButton.frame.size.width = size.width
    myButton.title = "blublublublub"
    

    If someone want to change the size outside @IBAction you need to use dispatch:

    dispatch_async( dispatch_get_main_queue()){
            self.myButton.title = "blublublublub"
            var size = self.myButton.attributedTitle.size
            self.myButton.frame.size.width = size.width
            self.myButton.title = "blublublublub"
        }