Swift 4 attributedString get typing attributes

2019-02-13 03:48发布

问题:

I am trying to create AttributedString and add the attributes from

typingAttributes(from textView)

The problem is that

.typingAttributes

return

[String, Any]

and

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

needs

[NSAttributedStringKey: Any]

My code:

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

回答1:

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


回答2:

Even better solution I think. I created extension.

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



回答3:

Here is my helper class, which I use custom fonts

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