Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust UIButton font size to width

Try this:

button.titleLabel?.numberOfLines = 1
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = .byClipping //<-- MAGIC LINE

I'm not sure why this does the trick but it does :)


button.titleLabel.adjustsFontSizeToFitWidth = YES;

should do the work on its own if you are using Auto-Layout and have set a constraint on the button's width.

The other options (minimum scale factor, number of lines etc) can still be used to customize further according to your needs, but are not required.


The answer from EliBud doesn't work on iOS 8. I found a solution which works on iOS 8. Below is a swift code:

let label = self.button?.titleLabel
label?.minimumScaleFactor = 0.01
label?.adjustsFontSizeToFitWidth = true
label?.font = UIFont.systemFontOfSize(100)

You can play with label?.lineBreakMode as I found that results varies for different break modes.


Swift 4 extension

extension UIButton {
    @IBInspectable var adjustFontSizeToWidth: Bool {
        get {
            return self.titleLabel?.adjustsFontSizeToFitWidth
        }
        set {
            self.titleLabel?.numberOfLines = 1
            self.titleLabel?.adjustsFontSizeToFitWidth = newValue;
            self.titleLabel?.lineBreakMode = .byClipping;
            self.titleLabel?.baselineAdjustment = .alignCenters 
        }
    }
}

enter image description here


in latest swift this seems to work for me

button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByClipping

iOS 10.3 solution based on the other answers here:

    button.titleLabel!.numberOfLines = 1
    button.titleLabel!.adjustsFontSizeToFitWidth = true
    button.titleLabel!.baselineAdjustment = .alignCenters

Nobody mentioned baselineAdjustment yet; I needed it because the button label becomes vertically misaligned after adjustsFontSizeToFitWidth takes effect. Apple's baselineAdjustment documentation:

If the adjustsFontSizeToFitWidth property is set to true, this property controls the behavior of the text baselines in situations where adjustment of the font size is required. The default value of this property is alignBaselines. This property is effective only when the numberOfLines property is set to 1.


FWIW, I could never get the label perfectly aligned.