Swift 4属性String获取键入属性



我正在尝试创建属性string,并添加

的属性

typingAttributes(from textView)

问题是

.typingAttributes

返回

[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

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

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

最新更新