Swift 4 attributedString get typing attributes

前端 未结 3 1098
轻奢々
轻奢々 2021-01-05 01:52

I am trying to create AttributedString and add the attributes from

typingAttributes(from textView)

The problem is that

.typingAt

相关标签:
3条回答
  • 2021-01-05 02:15

    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
    }
    }
    
    0 讨论(0)
  • 2021-01-05 02:18

    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)
            })
        }
    }
    
    0 讨论(0)
  • 2021-01-05 02:30

    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

    0 讨论(0)
提交回复
热议问题