Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Adjusting fontSize to fit the width of the layout (programmatically)

I've been looking for something to dynamically adjust my fontSize to fit the width of my layout box. But all the answers I can find, is either to use this:

label.adjustsFontSizeToFitWidth = true 

Which does work. But only if I don't have setTranslatesAutoresizingMaskIntoConstraints set to false.

Please note that I don't use storyboards. So to have full control over my other constraints I need this line:

label.setTranslatesAutoresizingMaskIntoConstraints(false) 

So how can I adjust the font size to fit the width without using storyboard and when I can't use adjustsFontSizeToFitWidth.

After I figure out how to adjust the font size to fit the width. I also need to adjust the height of the layout box to fit the font size. There seems to be documentation on that though, but if you happen to know the answer of this as well, it would be greatly appreciated.

Thanks in advance

like image 316
MLyck Avatar asked Feb 26 '15 03:02

MLyck


2 Answers

Try the following commands for your label:

label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.2 

And try to change the lines of the label to 0 and 1 (check both cases):

label.numberOfLines = 0 // or 1 
like image 53
Roi Mulia Avatar answered Sep 22 '22 16:09

Roi Mulia


MinimumScaleFactor range is 0 to 1. So we are setting the MinimumScaleFactor with respect to our font size as follows

Objective C

[lb setMinimumScaleFactor:10.0/[UIFont labelFontSize]]; lb.adjustsFontSizeToFitWidth = YES; 

Swift 3.0

lb.minimumScaleFactor = 10/UIFont.labelFontSize lb.adjustsFontSizeToFitWidth = true 
like image 20
Vinu David Jose Avatar answered Sep 21 '22 16:09

Vinu David Jose