Swift 4 attributedString 获取类型属性

Swift 4 attributedString get typing attributes

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

的属性

typingAttributes(from textView)

问题是

.typingAttributes

return

[String, Any]

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

我认为更好的解决方案。我创建了扩展。

public extension Dictionary {
    func toNSAttributedStringKeys() -> [NSAttributedStringKey: Any] {
        var atts = [NSAttributedStringKey: Any]()

        for key in keys {
            if let keyString = key as? String {
                atts[NSAttributedStringKey(keyString)] = self[key]
            }
        }

        return atts
    }
}

https://gist.github.com/AltiAntonov/f0f86e7cd04c61118e13f753191b5d9e

这是我的助手 class,我使用自定义字体

import UIKit

struct AttributedStringHelper {

enum FontType: String {
    case bold = "GothamRounded-Bold"
    case medium = "GothamRounded-Medium"
    case book = "GothamRounded-Book"
}

static func getString(text: String, fontType: FontType, size: CGFloat, color: UIColor, isUnderlined: Bool? = nil) -> NSAttributedString {

    var attributes : [NSAttributedStringKey : Any] = [
        NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont(name: fontType.rawValue, size: size)!,
        NSAttributedStringKey.foregroundColor : color]

    if let isUnderlined = isUnderlined, isUnderlined {
        attributes[NSAttributedStringKey.underlineStyle] = 1
    }

    let attributedString = NSAttributedString(string: text, attributes: attributes)
    return attributedString
}
}