How to dynamically change the font size in auto layout iOS?
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+
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
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;
You can do this by using size classes.each display dimension using a size class, this will result in four abstract devices: Regular width-Regular Height, Regular width-Compact Height, Compact width-Regular Height and Compact width-Compact Height.The table below shows the iOS devices and their corresponding size classes.￼
To set the font size for this particular size class, first select the
UILabel. Under the Attributes inspector, you should see a plus (+) button next to the font field. Click the + button and select Compact Width > Regular Height (Or as per your requirement select width & Height). You will then see a new entry for the Font option, which is dedicated to that particular size class. Keep the size intact for the original Font option but change the size of wC hR (OR as per your selection) font field to required points (for example 14).