Swift 4 attributedString get typing attributes

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!