gpt4 book ai didi

Swift 4 attributedString 获取输入属性

转载 作者:IT王子 更新时间:2023-10-29 05:49:09 24 4
gpt4 key购买 nike

我正在尝试创建 AttributedString 并添加来自

的属性

typingAttributes(来自 textView)

问题是

.typingAttributes

返回

[字符串,任意]

NSAttributedString(string:.. , attributes:[])

需要

[NSAttributedStringKey: Any]

我的代码:

NSAttributedString(string: "test123", attributes: self.textView.typingAttributes)

我不想在循环中创建遍历所有键并将它们更改为

NSAttributedStringKey

最佳答案

您可以将 [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)

这里有一个可能的扩展方法,它是仅限于带有字符串键的字典:

extension Dictionary where Key == String {

func toAttributedStringKeys() -> [NSAttributedStringKey: Value] {
return Dictionary<NSAttributedStringKey, Value>(uniqueKeysWithValues: map {
key, value in (NSAttributedStringKey(key), value)
})
}
}

关于Swift 4 attributedString 获取输入属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46470670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com