Clicky

iOS Dev Nugget 171 Dynamic Type

.

Need to run a code review on your codebase? Hire me

In iOS 7, along with the complete visual refresh, Dynamic Type was introduced. Users can adjust their preferred global text size in Settings.app > General > Accessibility > Larger Text and apps that support Dynamic Type can automagically adjust text to adapt.

The simplest way to get this to work is by creating UIFont using preferredFontForTextStyle: and passing in one of the text styles listed in the UIFontDescriptor class doc. These are:

UIFontTextStyleHeadline
UIFontTextStyleSubheadline
UIFontTextStyleBody
UIFontTextStyleFootnote
UIFontTextStyleCaption1
UIFontTextStyleCaption2

Instead of creating a UIFont instance with an explicit point size, do this:

UIFont* font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];

Sometimes, you'll find that you want something that looks like the body font, but in bold. You can create a new UIFontDescriptor based on the one specified by the text style.

UIFont* bodyFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
UIFont* font = [UIFont fontWithDescriptor:[[bodyFont fontDescriptor] fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:bodyFont.pointSize];

UIFontDescriptors are a way to describe font attributes and can be used to create a font. Text styles such as UIFontTextStyleBody are strings that map to an UIFontDescriptor instance predefined by Apple to look nice given the user's chosen text size.

When the user tweaks the slider while your app is running (in the background), you'll want to refresh your UI to reflect the updated font sizes. You can do this by observing UIContentSizeCategoryDidChangeNotification and assigning new fonts to your UI elements (such as UILabel).

Note that UI element sizes will likely change when font sizes changes. You'll have to either use Auto Layout, or remember to re-compute frame sizes when that happens.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues