Swift 4 Label attributes

前端 未结 7 697
死守一世寂寞
死守一世寂寞 2020-12-31 09:14

I\'m moving from swift 3 to swift 4. I have UILabels that I am giving very specific text properties to the label. I\'m getting an \'unexpectedly found nil while unwrapping

7条回答
  •  感情败类
    2020-12-31 09:38

    In Swift 4.0+, attributed string accepts json (dictionary) with key type NSAttributedStringKey or NSAttributedString.Key.

    So you must change it from [String : Any] to

    Swift 4.1 & below - [NSAttributedStringKey : Any] &
    Swift 4.2 & above - [NSAttributedString.Key : Any]

    Swift 4.2

    Initialiser for AttributedString in Swift 4.2 is changed to [NSAttributedString.Key : Any]?

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

    Here is sample working code.

    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)
    

    Swift 4.0

    Initialiser for AttributedString in Swift 4.0 is changed to [NSAttributedStringKey : Any]?.

    public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)
    

    Here is sample working code.

    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)
    

    Look at this Apple Document, for more info: NSAttributedString - Creating an NSAttributedString Object

提交回复
热议问题