How to apply bold and italics to an NSMutableAttributedString range?
If you're applying each (bold or italic) trait individually, you need to make sure that bold and italic ranges don't overlap or one trait will overwrite the other.
The only way to apply both bold and italic traits to a range is to use a font which is both bold and italic, and apply the both traits at once.
let str = "Normal Bold Italics BoldItalics"
let font = UIFont(name: "Avenir", size: 14.0)!
let italicsFont = UIFont(name: "Avenir-BookOblique", size: 14.0)!
let boldFont = UIFont(name: "Avenir-Heavy", size: 14.0)!
let boldItalicsFont = UIFont(name: "Avenir-HeavyOblique", size: 14.0)!
let attributedString = NSMutableAttributedString(string: str, attributes: [NSFontAttributeName : font])
attributedString.addAttribute(NSFontAttributeName, value: boldFont, range: NSMakeRange(7, 4))
attributedString.addAttribute(NSFontAttributeName, value: italicsFont, range: NSMakeRange(12, 7))
attributedString.addAttribute(NSFontAttributeName, value: boldItalicsFont, range: NSMakeRange(20, 11))
In Swift and using an extension:
extension UIFont {
func withTraits(_ traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
// create a new font descriptor with the given traits
guard let fd = fontDescriptor.withSymbolicTraits(traits) else {
// the given traits couldn't be applied, return self
return self
}
// return a new font with the created font descriptor
return UIFont(descriptor: fd, size: pointSize)
}
func italics() -> UIFont {
return withTraits(.traitItalic)
}
func bold() -> UIFont {
return withTraits(.traitBold)
}
func boldItalics() -> UIFont {
return withTraits([ .traitBold, .traitItalic ])
}
}
Example:
if let font = UIFont(name: "Avenir", size: 30) {
let s = NSAttributedString(string: "Hello World!", attributes: [ NSFontAttributeName: font.italic() ])
let t = NSAttributedString(string: "Hello World!", attributes: [ NSFontAttributeName: font.boldItalic()) ])
}