简体   繁体   中英

Swift NSAttributedString custom fonts

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.

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
}

For Swift 3 , here's an update that worked for me:

First you'll set up the font and then create a textAttribute with the NSFontAttributeName :

let font = UIFont(name: "Raleway-SemiBold", size: 16)
textAttribute = [NSFontAttributeName: font as Any, NSForegroundColorAttributeName: UIColor.black]

You can then apply textAttribute to your label, textfield etc.

You Just have to write the correct string name of your font.

  1. Don't write the name that is font file name. (like bodoni-mt-bold.ttf its the file name i have downloaded from any site).

  2. To find out the exact font name follow the image below.

  3. Go to your label select it and go to custom font and then see the name of your custom font in its family. if your custom font name is there then copy that name and past it as a string where u wanna use it. (Note you can't copy font name text you have to write else where then past it)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM