Search code examples
iosobjective-cswiftuibuttonuilabel

Adjust font size of text to fit in UIButton


I want to make sure the button text fits into a UIButton, while the UIButton has a fixed size.

Of course I can access the titleLabel of the UIButton. In a label I would set autoshrink to minimum font scale which seems to correspond to

self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;

, but doesn't really behave the same, since it only makes the text fits horizontally into the bounds, not vertically, thereby not changing the font size.

How can i actually adjust the font size of a label programmatically to make the text fit into the label bounds (as shown in Goal in the picture below) ?

adjustsFontSizeToFitWidth does not actually adjust the font size to fit the frame, only the width

I already tried

self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;

without success, always ended up as in adjustsFontSizeToFitWidth on the left side of the pic above.

Edit: The solution also has to be ios7 compliant


Solution

  • self.mybutton.titleLabel.minimumScaleFactor = 0.5f;
    self.mybutton.titleLabel.numberOfLines = 0;   <-- Or to desired number of lines
    self.mybutton.titleLabel.adjustsFontSizeToFitWidth = YES;
    

    ... did the trick, after layoutIfNeeded in viewDidLoad As it turns out, all those must be set to actually adjust the font-size, not just making it fit into the frame.

    Update for Swift 3:

    mybutton.titleLabel?.minimumScaleFactor = 0.5
    mybutton.titleLabel?.numberOfLines = 0   <-- Or to desired number of lines
    mybutton.titleLabel?.adjustsFontSizeToFitWidth = true