user3477955
user3477955

Reputation: 91

How to adjust font size of text in a UIButton to fit the height programmatically in Swift?

I have a button, and set its frame & title:

let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(x, y, width, height)
button.setTitle("Shuffle", forState: UIControlState.Normal)

I have been using the below to change the width of text in the UIButton:

button.titleLabel?.adjustsFontSizeToFitWidth = true

This does adjust the font size to the width, but not the height of the button. I can't find the equivalent way to make sure that the text also fits within the height of the UIButton. I also tried the below, but it didn't work for me:

button.titleLabel?.drawTextInRect(button.frame)

Upvotes: 2

Views: 1455

Answers (1)

ZeMoon
ZeMoon

Reputation: 20284

Have a look at the baselineAdjustment property of UILabel:

It can be used with a UIButton as follows:

button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters

Upvotes: 2

Related Questions