Swift 4标签属性
我正在从swift 3移动到swift 4.我有UILabels,我将非常具体的文本属性赋予标签。当strokeTextAttributes被初始化时,我得到'意外发现的零,同时展开可选值'错误。我完全失去坦率。Swift 4标签属性
在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)
@ Larme对不需要的.rawValue
的评论是正确的。
此外,您还可以避开力施放,使用显式类型崩溃代码:
let strokeTextAttributes: [NSAttributedStringKey: Any] = [
.strokeColor : UIColor.black,
.foregroundColor : UIColor.white,
.strokeWidth : -2.0,
.font : UIFont.boldSystemFont(ofSize: 18)
]
这摆脱了重复NSAttributedStringKey.
,太多。
斯威夫特4建议你自己的解决方案。在Swift 4.0中,属性字符串接受键类型为NSAttributedStringKey
的json(字典)。所以,你必须将其从[String : Any]
更改为[NSAttributedStringKey : Any]
初始化器在斯威夫特4.0 AttributedString
改为[NSAttributedStringKey : Any]?
这里是雨燕4.0
public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)
初始化器声明/功能下面是示例工作代码。
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)
现在看这个笔记从苹果:NSAttributedString - Creating an NSAttributedString Object
NSAttributedStringKey.strokeColor.rawValue
的类型是String
NSAttributedStringKey.strokeColor
的类型为NSAttributedStringKey
因此,它无法String
转换为NSAttributedStringKey
。 你必须使用如下:
let strokeTextAttributes: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.strokeColor : UIColor.black,
NSAttributedStringKey.foregroundColor : UIColor.white,
NSAttributedStringKey.strokeWidth : -2.0,
NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
]
'NSAttributedStringKey.strokeColor.rawValue' =>'NSAttributedStringKey.strokeColor'呢? – Larme
与一般编程相比,Swift是一个绝对的噩梦,也是重要的一步。 – RunLoop