Swift NSAttributedString自定义字体

Raz*_*riu 9 nsattributedstring custom-font ios swift

我已经阅读了不同的解决方案,但似乎没有任何效果.此代码创建一个零异常:

[NSFontAttributeName: UIFont(name: "Raleway-SemiBold", size: 16)!]
Run Code Online (Sandbox Code Playgroud)

我正确安装了字体,它们在应用程序中正确显示(目标设置).
我尝试添加应用程序提供的字体plist但没有发生任何事情.我无法编辑数组中的项目:(they are item0 : string : Raleway-SemiBold.tff).

所以基本上我被卡住了......有时Swift和Apple环境对于程序员来说是很好的,有时候(大多数时候),它们太缺陷了,需要这么多的解决方法来达到预期的结果.

非常感谢您的帮助.

Aar*_*ger 16

你得到一个例外,因为UIFont(name: "Raleway-SemiBold", size: 16)返回nil并且你强行解开它!.

相反,使用条件展开:

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
}
Run Code Online (Sandbox Code Playgroud)

您可以使用UIFont's' familyNames()fontNamesForFamilyName(_:)方法来获取所需的确切字符串.

斯威夫特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
}
Run Code Online (Sandbox Code Playgroud)