Swift 4 Label属性

Blu*_*lue 13 nsattributedstring uilabel ios swift swift4

我正在从swift 3转到swift 4.我有UILabels,我给标签提供了非常具体的文本属性.初始化strokeTextAttributes时,我在获取"意外发现nil时解包可选值"错误.坦白说,我完全迷失了.

在swift 3中,strokeTextAttributes是[String:Any],但是swift 4引发了错误,直到我将其更改为下面的内容.

let strokeTextAttributes = [
    NSAttributedStringKey.strokeColor.rawValue : UIColor.black,
    NSAttributedStringKey.foregroundColor : UIColor.white,
    NSAttributedStringKey.strokeWidth : -2.0,
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
    ] as! [NSAttributedStringKey : Any]


chevronRightLabel.attributedText = NSMutableAttributedString(string: "0", attributes: strokeTextAttributes)
Run Code Online (Sandbox Code Playgroud)

Xav*_*ler 30

@ Larme关于不需要的评论.rawValue是正确的.

此外,您可以使用显式类型避免强制转换使代码崩溃:

let strokeTextAttributes: [NSAttributedString.Key: Any] = [
    .strokeColor : UIColor.black,
    .foregroundColor : UIColor.white,
    .strokeWidth : -2.0,
    .font : UIFont.boldSystemFont(ofSize: 18)
]
Run Code Online (Sandbox Code Playgroud)

这也消除了重复性NSAttributedString.Key..


Kru*_*nal 15

Swift 4.0+,属性字符串接受json(字典)与键类型NSAttributedStringKeyNSAttributedString.Key.

所以,你必须从改变[String : Any]

Swift 4.1及以下 - [NSAttributedStringKey : Any]&
Swift 4.2及以上 - [NSAttributedString.Key : Any]

Swift 4.2

AttributedStringSwift 4.2中的Initialiser 更改为[NSAttributedString.Key : Any]?

public init(string str: String, attributes attrs: [NSAttributedString.Key : Any]? = nil)
Run Code Online (Sandbox Code Playgroud)

这是示例工作代码.

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedString.Key.strokeColor : UIColor.black,
     NSAttributedString.Key.foregroundColor : UIColor.white,
     NSAttributedString.Key.strokeWidth : -2.0,
     NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedString.Key : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)
Run Code Online (Sandbox Code Playgroud)

Swift 4.0

AttributedStringSwift 4.0中的Initialiser 更改为[NSAttributedStringKey : Any]?.

public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)
Run Code Online (Sandbox Code Playgroud)

这是示例工作代码.

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedStringKey.strokeColor : UIColor.black,
     NSAttributedStringKey.foregroundColor : UIColor.white,
     NSAttributedStringKey.strokeWidth : -2.0,
     NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedStringKey : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)
Run Code Online (Sandbox Code Playgroud)

查看此Apple文档,了解更多信息:NSAttributedString - 创建NSAttributedString对象