Swift NSAttributedString custom fonts

Razvan Soneriu picture Razvan Soneriu · Mar 25, 2015 · Viewed 14.2k times · Source

I've read around for different solutions but nothing seems to work. This code creates a nil exception:

[NSFontAttributeName: UIFont(name: "Raleway-SemiBold", size: 16)!]

I have the fonts installed properly and they show up correctly in the app (target is set).
I tried to add the application provided fonts in the plist but nothing happened. I can't edit the items in the array: (they are item0 : string : Raleway-SemiBold.tff).

So basically I'm stuck... Sometimes Swift and Apple environments are great for a programmer, other times (most of the time), they are sooo faulty and need so many workarounds to reach the expected results.

Many thanks in advance for any help.

Answer

Aaron Brager picture Aaron Brager · Mar 25, 2015

You're getting an exception because UIFont(name: "Raleway-SemiBold", size: 16) returns nil and you're force-unwrapping it with !.

Instead, use conditional unwrapping:

if let font = UIFont(name: "Raleway-SemiBold", size: 16) {
    let attributes = [NSFontAttributeName: font]
    // do something with attributes
} else {
    // The font "Raleway-SemiBold" is not found
}

You can use UIFont's familyNames() and fontNamesForFamilyName(_:) methods to get the exact string required.

Swift 4

if let font = UIFont(name: "Raleway-SemiBold", size: 16) {
    let attributes = [NSAttributedStringKey.font: font]
    // do something with attributes
} else {
    // The font "Raleway-SemiBold" is not found
}