Swift 4 attribute String gets input attributes

I am trying to create an AttributedString and add attributes from

typingAttributes(from textView)

The problem is

.typingAttributes

return

[String, Any]

and

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

required

[NSAttributedStringKey: Any]

My code is:

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

I do not want to create all the keys in a loop and change them to

 NSAttributedStringKey 
+7
swift ios11 swift4 xcode9
source share
3 answers

You can map the dictionary [String: Any] to the Dictionary [NSAttributedStringKey: Any] 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 this purpose. limited 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) }) } } 
+7
source share

Even the best solution, I think. I created an 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

+2
source share

Here is my helper class that 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 } } 
0
source share

All Articles