首页 > 解决方案 > Create custom NSAttributedString.Key

问题描述

I'm trying to build a simple note app. At the moment, I'm focusing on the possibility to set the text with different text styles (e.g. body, headline, bold, italic, etc.). I used a NSAttributedString to set the different text styles. Now, I'd like to detect which style has been applied to the selected text.

I thought a good way to do it would have been to create a custom NSAttributedString.Key, so that I can assign it when setting the attributes (e.g. .textStyle: "headline", and read it when I need to detect it. I tried implementing it as an extension of NSAttributedString.Key but without success. What would be the correct way to do it? Is there a better alternative?

标签: iosswift

解决方案


You can simply create a TextStyle enumeration and set your cases "body, headline, bold, italic, etc" (You can assign any value to them if needed). Then you just need to create a new NSAttributedString key:


enum TextStyle {
    case body, headline, bold, italic
}

extension NSAttributedString.Key {
    static let textStyle: NSAttributedString.Key = .init("textStyle")
}

Playground Testing

let attributedString = NSMutableAttributedString(string: "Hello Playground")

attributedString.setAttributes([.textStyle: TextStyle.headline], range: NSRange(location: 0, length: 5))

attributedString.enumerateAttributes(in: NSRange(location: 0, length: attributedString.length), options: []) { attributes, range, stop in
    print(attributes, range, stop )
    print(attributedString.attributedSubstring(from: range))
}

推荐阅读