2017-10-09 77 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) 
]