Swift 4 Label attributes
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
@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.
NSAttributedStringKey.strokeColor.rawValue
is of typeString
NSAttributedStringKey.strokeColor
is of typeNSAttributedStringKey
So its unable to convert String
to NSAttributedStringKey
.
You have to use like below:
let strokeTextAttributes: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.strokeColor : UIColor.black,
NSAttributedStringKey.foregroundColor : UIColor.white,
NSAttributedStringKey.strokeWidth : -2.0,
NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
]