0

In CSS, you have the font-size property that can be used to specify font sizes relative to the rest of the text.

What would it take to implement a custom relative font-size attribute in iOS (requiring only iOS 7 compatibility)? Are there any third-party solutions that already implement this?

(I would expect the solution to be useful for everything that supports attributed text: UILabel, UITextView, ... the titleLabel in a UIButton, etc.)

1 Answer 1

1

Let's say you want to define attributes for your own custom headers that are relative to the user's preferred body font size (i.e, Dynamic Type).

UIFontDescriptor *bodyFontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody];

NSNumber *bodyFontSize = bodyFont.fontAttributes[UIFontDescriptorSizeAttribute];

float bodyFontSizeValue = [bodyFontSize floatValue];

UIFont *headerOneFont = [UIFont fontWithDescriptor:bodyFontDescriptor size:bodyFontSizeValue * 3.0f];

NSDictionary *headerOneAttributes = @{NSFontAttributeName : headerOneFont};

UIFont *headerTwoFont = [UIFont fontWithDescriptor:bodyFontDescriptor size:bodyFontSizeValue * 2.0f];

NSDictionary *headerTwoAttributes = @{NSFontAttributeName : headerTwoFont};

This code is based on code from Chapters 4 and 5 of "iOS 7 by Tutorials", by raywenderlich.com.

The attribute dictionaries can be used to initialize attributed string objects, which in turn, can be displayed in UILabels, UITextViews, and UITextFields.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.