Dynamic Font support for UIButton

I tried dynamic font support for my app and it worked smoothly for all my Labels and textfiled. But, After infinite trials I could not find any way to make my button resize when we use the iOS Large text feature to utilize dynamic fonts. Does not even fount any resource on internet for Dyanamic font support for UIButton. My inference is Apple does not support dynamic font for Buttons. Is it true. If not, Any help is much appreciated.

You cannot do it from IB.


But you should be able to do it programmatically ; in viewDidLoad, add:

button.titleLabel?.adjustsFontSizeToFitWidth = true

button.titleLabel?.minimumScaleFactor = 0.5

See detailed discussion here:

https://stackoverflow.com/questions/46067504/xcode-swift-how-to-change-button-font-size-dynamically-according-to-the-size-of

Right now I have the same impression. Pitty.

For anyone who finds this while looking for their answer:
As you know, you have to have used a "Text Style" font for it to be resizeable (although there are other ways to accomplish this).

Once you've done that, just doing:

button.titleLabel?.adjustsFontForContentSizeCategory = true

in code (such as in viewDIdLoad()) should get you what you want.

This answer is addressing allowing fonts to shrink rather than vary dynamically.


I just wanted to mention (for others who find this answer in a search) that in 2020, there is another step that is necessary, which is:

button.titleLabel?.lineBreakMode = .byClipping

(or any of the ".byTruncating..." options; it can NOT be either of the "wrapping" options, which are the default inside a button.)


You might also want to do

button.titleLabel?.numberOfLines = 1

or some other value of your choice. The default inside a button is 0, which means as many lines as needed, which might give you less reduction that you want. Now here's an interesting tip. If you change lineBreakMode, it sets numberOfLines to 1! If you want to set numberOfLines to something else, you have to do that last.


I recommend the following:

extension UIButton

{

func allowTextToScale(minFontScale: CGFloat = 0.5, numberOfLines: Int = 1)

{

self.titleLabel?.adjustsFontSizeToFitWidth = true

self.titleLabel?.minimumScaleFactor = minFontScale

self.titleLabel?.lineBreakMode = .byTruncatingTail

// Caution! The above causes numberOfLines to become 1,

// so this next line must be AFTER that one.

self.titleLabel?.numberOfLines = numberOfLines

}

}


Barry

Dynamic Font support for UIButton
 
 
Q