I am trying to create AttributedString and add the attributes from
typingAttributes(from textView)
The problem is that
.typingAttributes
return
[String, Any]
and
NSAttributedString(string:.. , attributes:[])
needs
[NSAttributedStringKey: Any]
My code:
NSAttributedString(string: "test123", attributes: self.textView.typingAttributes)
I don't want to create for in cycle to go through all keys and change them to
NSAttributedStringKey
You can map the [String: Any]
dictionary to a
[NSAttributedStringKey: Any]
dictionary with
let typingAttributes = Dictionary(uniqueKeysWithValues: self.textView.typingAttributes.map {
key, value in (NSAttributedStringKey(key), value)
})
let text = NSAttributedString(string: "test123", attributes: typingAttributes)
Here is a possible extension method for that purpose, it is restricted to dictionaries with string keys:
extension Dictionary where Key == String {
func toAttributedStringKeys() -> [NSAttributedStringKey: Value] {
return Dictionary<NSAttributedStringKey, Value>(uniqueKeysWithValues: map {
key, value in (NSAttributedStringKey(key), value)
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With