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
892 views
in Technique[技术] by (71.8m points)

xcode - How to dynamically change the font size in auto layout iOS?

I want to fit my text in a UILabel, but for different iPhone the size of the UILabel is changing, as I'm using auto layout, but I cannot fix the font size, so my text is cutting out.

Is there any way I can set any constraint so that the text fits in the UILabel dynamically?

See here the text got cut, because of different screen resolution

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should use autoshrink.

Since all iPhones have the same Compact width size class when in portrait mode, you can't rely on this to handle your label size.


Previews are for iPhone5, iPhone6 and iPhone 6+

enter image description here

In the inspector, you must select minimum font scale or minimum font size in front of Autoshrink. This enables the content to change the size of the font to fit in the label.

Here, I set minimum font scale to 0,5 so the minimum size is half of the current size (31.0). The text will try to fit until it reaches the minimum scale/size.

(Generally do not use "Tighten letter spacing" for this purpose. Tighten letter spacing uses the same font size and reduces spacing between letters. It can make the label up to 5% tighter before truncating, but it's not effective when minimum font scale/size is enabled.)


You may want to test with a wide screen device such as the iPad Pro, and also on a smaller screen such as the iPhone 4S. As a good practice you should test with different user system font sizes, you can set them in Settings>General>Accessibility>Larger Text.

Autoshrink will not adjust the font size bigger than the one set on the label, that means if you make the label the same width as the screen but leave the font size to 14, it will try to increase the font size until it reaches that size.

To make it actually work, select a big font size.

You can still combine autoshrink with size classes to change the maximum font size depending on the device/the orientation.


In case you want to use autoshrink with UIButtons, you can still set this behavior with two lines of code.

myButton.titleLabel.minimumScaleFactor = 0.5;
myButton.titleLabel.adjustsFontSizeToFitWidth = YES;

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

...