【问题标题】:Why are NSAttributedString's attributes now of type [NSAttributedStringKey: Any] but UITextView's typingAttributes are still of type [String: Any]? [duplicate]为什么 NSAttributedString 的属性现在是 [NSAttributedStringKey: Any] 类型,但 UITextView 的 typingAttributes 仍然是 [String: Any] 类型? [复制]
【发布时间】:2017-10-19 21:21:24
【问题描述】:

我曾经能够生成NSAttributedStrings 并使用[String: Any] 类型的相同属性字典(尤其是相同的键)设置UITextViewtypingAttributes。从 iOS 11 开始,我不得不将[String: Any] 属性更改为[NSAttributedStringKey: Any]attributes 以生成NSAttributedStrings,但UITextViews 仍然是[String: Any] 类型。为什么?

【问题讨论】:

  • 仅供参考 - 这与 Swift 4 无关。NSAttributedStringKey 的使用是 iOS 11 等 API 的变化。无论您使用 Swift 4、Swift 3 还是Objective-C。
  • 奇怪,编译时警告只有在我在 Xcode 9 中从 Swift 3.2 转换为 Swift 4 后才会弹出
  • 对我来说似乎也没有统一。

标签: ios swift uitextview nsattributedstring swift4


【解决方案1】:

不知道为什么它也不是[NSAttributedStringKey: Any],但你可以像这样转换它

func ConvertToTypingAttributes(_ attr: [NSAttributedStringKey: Any]) -> [String: Any] {
    var result = [String: Any]()
    for (k,v) in attr {
        result[k.rawValue] = v
    }
    return result
}

用法:

var txtView = UITextView()
let p: [NSAttributedStringKey: Any] = [NSAttributedStringKey.backgroundColor: UIColor.green]
txtView.typingAttributes = ConvertToTypingAttributes(p)

【讨论】:

  • 谢谢,但我的问题不是寻求一种转换方式,而是一种解释。
  • 由于问题不是要求转换,因此我不会将此添加为答案。这是另一种选择:extension Dictionary where Key == NSAttributedStringKey { func asTypingAttributes() -> [String: Any] { var result = [String: Any]() for (key, value) in self { result[key.rawValue] = value } return result } }
猜你喜欢
  • 1970-01-01
  • 2021-10-02
  • 2023-04-03
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2019-10-21
相关资源
最近更新 更多