Swift 4的attributesString得到了输入属性

时间:2017-09-28 13:40:43

标签: swift ios11 swift4 xcode9

我正在尝试创建AttributedString并添加

中的属性

typingAttributes(from textView)

问题在于

.typingAttributes

返回

[String, Any]

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

需要

[NSAttributedStringKey: Any]

我的代码:

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

我不想创建for循环来遍历所有键并将其更改为

NSAttributedStringKey

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

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

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