本文介绍了Swift 4 attributedString获取输入属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建AttributedString并从

I am trying to create AttributedString and add the attributes from

typingAttributes(来自textView)

问题是

.typingAttributes

返回

[String,Any]

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

需要

[NSAttributedStringKey:任何]

我的代码:

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

推荐答案

您可以将 [String:Any] 字典映射到 [NSAttributedStringKey:Any] 字典与

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 isrestricted 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)
        })
    }
}

这篇关于Swift 4 attributedString获取输入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 23:42