Swift 4 Label Attributes

I’m moving from fast 3 to fast 4. I have UILabels that I give very specific text properties to the label. When initializing strokeTextAttributes, I get the error message "unexpectedly found nil while unwrapping optional value". I am completely lost to be frank.

In swift 3, the parameter strokeTextAttributes was [String: Any], but swift 4 threw errors until I changed it to what it is below.

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)
+4
source share
3 answers

@Larme's comment is .rawValuenot required.

In addition, you can avoid casting a force that causes your code to crash with explicit input:

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

It also eliminates the need for repetition NSAttributedStringKey..

+11

Swift 4 . Swift 4.0 json () NSAttributedStringKey. [String : Any] [NSAttributedStringKey : Any]

AttributedString Swift 4.0 [NSAttributedStringKey : Any]?

/ Swift 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)

Apple: NSAttributedString - NSAttributedString

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

Source: https://habr.com/ru/post/1687146/


All Articles