Alt*_*nov 8 swift swift4 ios11 xcode9
我正在尝试创建AttributedString并添加属性
typingAttributes(from textView)
问题是
.typingAttributes
返回
[String, Any]
和
NSAttributedString(string:.. , attributes:[])
需求
[NSAttributedStringKey: Any]
我的代码:
NSAttributedString(string: "test123", attributes: self.textView.typingAttributes)
Run Code Online (Sandbox Code Playgroud)
我不想创建for循环来遍历所有键并将其更改为
NSAttributedStringKey
Run Code Online (Sandbox Code Playgroud)
您可以将[String: Any]字典映射到
[NSAttributedStringKey: Any]字典
let typingAttributes = Dictionary(uniqueKeysWithValues: self.textView.typingAttributes.map {
key, value in (NSAttributedStringKey(key), value)
})
let text = NSAttributedString(string: "test123", attributes: typingAttributes)
Run Code Online (Sandbox Code Playgroud)
这是一个可能的扩展方法,它仅限于使用字符串键的字典:
extension Dictionary where Key == String {
func toAttributedStringKeys() -> [NSAttributedStringKey: Value] {
return Dictionary<NSAttributedStringKey, Value>(uniqueKeysWithValues: map {
key, value in (NSAttributedStringKey(key), value)
})
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4243 次 |
| 最近记录: |