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

12,299

Solution 1

Add this line for button object:

button.titleLabel?.adjustsFontSizeToFitWidth = true

Solution 2

If you work with the titleLabel you can use UILabel's adjustsFontSizeToFitWidth

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/index.html#//apple_ref/occ/instp/UILabel/adjustsFontSizeToFitWidth

and then use UILabel's minimumScaleFactor to set a minimum:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/index.html#//apple_ref/occ/instp/UILabel/minimumScaleFactor

Share:
12,299
muyiwa adenaike
Author by

muyiwa adenaike

Updated on June 04, 2022

Comments

  • muyiwa adenaike
    muyiwa adenaike almost 2 years

    I am trying to set the text in my UIButton programmatically, but the text becomes abbreviated when displayed in the button. Is there a way to adjust the font size of the text in the button to fit the width, through code? I have checked other questions, but the answers do not solve my problem. Thanks.