无法使用字体添加属性字符串Avenir Next Condensed [Swift 3]

时间:2016-10-10 10:27:42

标签: ios swift uitextview nsattributedstring

    let s = NSAttributedString(string: "Percentage", attributes: [NSFontAttributeName : UIFont(name : "Avenir Next Condensed", size : 20), NSUnderlineStyleAttributeName : NSUnderlineStyle.byWord])
    textView.attributedText = s

上面的代码出现以下错误: 因未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [_ SwiftValue _isDefaultFace]:无法识别的选择器发送到实例0x608000046930'

如果我将NSFontAttributeName更改为UIFont.boldSystemFont(ofSize:20),我可以看到粗体文本。 另外在添加NSUnderlineStyleAttributeName时,我根本看不到任何文本。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

两件事:

  • 您无法将Optional值传递给需要非空id值的位置。

attributes:参数在内部转换为NSDictionary,其值不能为零。但UIFont.init(name:size:)是一个易错的初始化程序,因此其返回类型为Optional。在Swift 3.0.0中,Swift在将其转换为非空_SwiftValue时生成类型为id的实例。并将其存储在attributes中。这在Objective-C方面完全没用。 (即使实际值不是零,也会发生这种情况。)

(Swift 3.0.1改善了这种情况的某些部分。)

  • 您无法将Swift枚举传递到需要id值的位置。

NSUnderlineStyle.byWord是一个Swift枚举。在Swift 3中,Swift在将其转换为_SwiftValue时会生成id类型的实例。

(Swift 3.0.1对这种情况没有改进。)

要修复上述两件事,你需要写下这样的东西:

if let font = UIFont(name: "Avenir Next Condensed", size: 20) {
    let s = NSAttributedString(string: "Percentage", attributes: [NSFontAttributeName: font, NSUnderlineStyleAttributeName: NSUnderlineStyle.byWord.rawValue])
    textView.attributedText = s
}