Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 Label attributes

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 optional value' error when strokeTextAttributes is being initialized. I'm totally lost to be frank.

In swift 3 the of 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)
like image 555
Blue Avatar asked Oct 09 '17 13:10

Blue


People also ask

What is UILabel in Swift?

A view that displays one or more lines of informational text.


1 Answers

@Larme's comment about the .rawValue not being needed is correct.

Also, you can avoid the force cast that crashes your code using explicit typing:

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

This gets rid of the repetitive NSAttributedString.Key., too.

like image 78
Xavier Lowmiller Avatar answered Oct 12 '22 01:10

Xavier Lowmiller