Reputation: 4289
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.)
Upvotes: 0
Views: 765
Reputation: 8918
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.
Upvotes: 1