2017-10-09 108 views
2

我正在从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) 
+3

'NSAttributedStringKey.strokeColor.rawValue' =>'NSAttributedStringKey.strokeColor'呢? – Larme

+0

与一般编程相比,Swift是一个绝对的噩梦,也是重要的一步。 – RunLoop

回答

8

@ Larme对不需要的.rawValue的评论是正确的。

此外,您还可以避开力施放,使用显式类型崩溃代码:

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

这摆脱了重复NSAttributedStringKey.,太多。

+0

如果我想同时使用dic和指定范围,有没有办法做到这一点? – Neko

+0

可以使用来自[NSAttributedStringKey](https://developer.apple.com/documentation/foundation/nsattributedstringkey)的所有'let let's,所以我不能支持范围。 – XML

0

斯威夫特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

0

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) 
]