The sixth item in my Swift Tool Belt is an extension for UIFont
. This extension will easily convert your font to be bold or italic. It can be useful if you use scaled fonts but need a different look.
Of course, you don’t need this extension to make a regular system font bold or italic. All you need are the following two lines to produce a system font of size 16 in bold or italic.
let boldFont = UIFont.boldSystemFont(ofSize: 16)
let italicFont = UIFont.italicSystemFont(ofSize: 16)
However, if you are using scaled fonts, it’s not as easy. You don’t necessarily know the size of the font you’re using because they dynamically scale based on the user’s preference. Scaled fonts are a wonderful thing for those of us with older eyes that can’t see as well as they used to. I always appreciate apps that take advantage of this accessibility feature.
The point of this extension is to convert a font’s traits to be bold or italic, while respecting the size.
label.font = UIFont.preferredFont(forTextStyle: .body)
label.adjustsFontForContentSizeCategory = true
The code above will give you a scaled font with the text style of .body
. However, there is no way to specify that you need a bold or italic font with the body style. My extension below can add that trait easily to the scaled font.
import UIKit
extension UIFont {
func withTraits(traits:UIFontDescriptorSymbolicTraits) -> UIFont {
let descriptor = fontDescriptor.withSymbolicTraits(traits)
return UIFont(descriptor: descriptor!, size: 0) //size 0 means keep the size as it is
}
func bold() -> UIFont {
return withTraits(traits: .traitBold)
}
func italic() -> UIFont {
return withTraits(traits: .traitItalic)
}
}
The extension is in two parts. The function withTraits
is more of a helper function that will take the font we are extending and apply the specified traits to it. The size parameter is set to zero, which means don’t change the font size from what it currently is. The two functions bold
and italic
are convenience functions.
Now, if I want a scaled font and want to make it bold, it’s as easy as this:
let boldFont = UIFont.preferredFont(forTextStyle: .headline).bold()
let italicFont = UIFont.preferredFont(forTextStyle: .footnote).italic()
It’s a simple but helpful extension that I hope you can use in your project.
This was exactly what I was looking for – thanks!
Nice!
You have to be careful with UIFontDescriptor! Check this out: https://stackoverflow.com/questions/34954956/why-uifontdescriptorsize-is-x200-slower-than-uifontnamesize