Scaling font size to label width iOS Swift

So, I recently started learning Swift and was wondering how you scale the text in your labels based on the screen size. I've seen a few questions like this, but they seem to be quite complex. I'm trying to do it like this, but it doesn't seem to work.

UIlabel1.adjustsFontSizeToFitWidth = true

I have linked the label to the code and set a few constraints. Width constraint Height constraint Center offset constraint X Vertical spatial constraint

The constraints are related to the view controller, so the actual label size scales with the screen size. Any ideas?

+3


source to share


2 answers


You can use Autoshrink

in storyboard

enter image description here



Change it to Minimum Font Scale

orMinimum Font Size

+1


source


From the documentation for adjustsFontSizeToFitWidth

:

Typically, label text is drawn with the font specified in the font property . If this property is set to true , and the property of the text in the text exceeds the bounding rectangle labels, label reduces the font size as long as the string does not match or the minimum font scale. The default value for this property is false . If you change it to true , make sure you also set the appropriate minimum font scale by changing the minimumScaleFactor property .

This tells you what you should set minimumScaleFactor

when using adjustsFontSizeToWidth

to scale the font.



But note that this scaling is only one direction. The font size will be smaller if required to display the text, but no larger than the font size you have set.

With this in mind, try setting the font size to match the largest screen your application will run on. On smaller screens, it will shrink to the size that the limit specified for minimumScaleFactor

.

+1


source







All Articles