I am trying to create AttributedString and add the attributes from
typingAttributes(from textView)
The problem is that
.typingAt
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
}
}
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)
})
}
}
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