I used to be able to generate NSAttributedString
s and set a UITextView
's typingAttributes
using the same attribute dictionary (most especially the same keys) of type [String: Any]
. Since iOS 11, I've had to change [String: Any]
attributes to [NSAttributedStringKey: Any]
attributes for generating NSAttributedString
s, yet UITextView
s still remain of type [String: Any]
. Why?
Asked
Active
Viewed 681 times
2

Aaron
- 6,466
- 7
- 37
- 75
-
1FYI - this has nothing to do with Swift 4. The use of `NSAttributedStringKey` is change in the API as of iOS 11, etc. It's the same whether you use Swift 4, Swift 3, or Objective-C. – rmaddy Oct 20 '17 at 00:28
-
Weird, the compile-time warnings only popped up after I converted from Swift 3.2 to Swift 4 in Xcode 9 – Aaron Oct 20 '17 at 01:28
-
Doesn't seem to be unified for me as well. – Jakub Truhlář Feb 21 '18 at 10:27
1 Answers
0
Not sure why it's not [NSAttributedStringKey: Any]
as well but nonetheless you can just convert it like so
func ConvertToTypingAttributes(_ attr: [NSAttributedStringKey: Any]) -> [String: Any] {
var result = [String: Any]()
for (k,v) in attr {
result[k.rawValue] = v
}
return result
}
USAGE:
var txtView = UITextView()
let p: [NSAttributedStringKey: Any] = [NSAttributedStringKey.backgroundColor: UIColor.green]
txtView.typingAttributes = ConvertToTypingAttributes(p)

TNguyen
- 1,041
- 9
- 24
-
Thanks, but my question wasn't asking for a way to convert it, rather an explanation. – Aaron Oct 19 '17 at 23:41
-
1Since the question isn't asking for a conversion, I won't add this as an answer. Here is another option: `extension Dictionary where Key == NSAttributedStringKey { func asTypingAttributes() -> [String: Any] { var result = [String: Any]() for (key, value) in self { result[key.rawValue] = value } return result } }` – Ben Packard Oct 20 '17 at 16:31