Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

ios - Adjust font size of text to fit in UIButton

I want to make sure the button text fits into a UIButton, while the UIButton has a fixed size.

Of course I can access the titleLabel of the UIButton. In a label I would set autoshrink to minimum font scale which seems to correspond to

self.myButton.titleLabel.adjustsFontSizeToFitWidth = YES;

, but doesn't really behave the same, since it only makes the text fits horizontally into the bounds, not vertically, thereby not changing the font size.

How can i actually adjust the font size of a label programmatically to make the text fit into the label bounds (as shown in Goal in the picture below) ?

adjustsFontSizeToFitWidth does not actually adjust the font size to fit the frame, only the width

I already tried

self.myButton.titleLabel.numberOfLines = 0;
self.myButton.titleLabel.minimumScaleFactor = 0.5f;

without success, always ended up as in adjustsFontSizeToFitWidth on the left side of the pic above.

Edit: The solution also has to be ios7 compliant

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...