NSAttributedStringKey给出未解析的标识符错误

Joh*_*m95 16 xcode ios swift

我正在按照在线教程构建一个杂志类型的iOS应用程序.我正在尝试使用NSAttributedStringKey,但不断收到如下所示的错误.有任何想法吗?

这是导致错误的代码行:

let attrs = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: font] as [NSAttributedStringKey : Any]
Run Code Online (Sandbox Code Playgroud)

Tib*_*mas 32

这些项目可能是Swift的不同版本.

在Swift 4中,NSFontAttributeName已被NSAttributedStringKey.font替换.

如此处所述NSFontAttributeName vs NSAttributedStringKey.font

需要确认它是否适用于低于ios11的版本


chr*_*son 20

您正尝试在iOS 11之前的版本(可能是iOS 10)上使用iOS 11 API.很惊讶您发现已经使用测试版功能的教程!

在此期间,试试这个.

let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]

这应该工作.


rma*_*ddy 7

您尝试使用的代码是在iOS 11中添加的新API.由于您使用的是Xcode 8,因此您不使用iOS 11.因此您需要使用当前(非beta)API.

let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
Run Code Online (Sandbox Code Playgroud)


Gau*_*iya 6

Swift 4.1和Xcode 9.3更改归属键值.

let strName = "Hello Stackoverflow"
let string_to_color2 = "Hello"        
let attributedString1 = NSMutableAttributedString(string:strName)
let range2 = (strName as NSString).range(of: string_to_color2)       
attributedString1.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: range2)
lblTest.attributedText = attributedString1
Run Code Online (Sandbox Code Playgroud)

您好,将是红色.