Adjust Font Size of Text to Fit in Uibutton

Adjust font size of text to fit in UIButton

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

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 :)

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

Add this line for button object:

button.titleLabel?.adjustsFontSizeToFitWidth = true

Xcode Swift: How to change button font size dynamically according to the size of the button?

More specifically:

yourUIButtonName.titleLabel?.adjustsFontSizeToFitWidth = true

will fit the font size to the width of the button, and adjusting the content insets will allow you to pad the edges of the text.

However, if you are trying to change the font size in some way that is not directly proportional to the size of the button's label, you will probably have to get the CGRect and math it out as necessary.

UIButton auto-adjust Button font size Swift

With auto layout you can set the space between buttons, and the max and min size. In code for all labels use:

self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.adjustsFontSizeToFitWidth = YES;

With this all labels adjust the text will size.

For adjust button to titleLabel use auto layout constraint for titleLabel. For examples:

  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.button.titleLabel
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:0.5
constant:0]];

This constraint define the height of titleLabel to 50% of self.view height. Now you can adapte the constraint for that you need.

This work in you code?

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

Have a look at the baselineAdjustment property of UILabel:

It can be used with a UIButton as follows:

button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters


Related Topics



Leave a reply



Submit