创建自定义 NSAttributedString.Key

Fra*_*sco 4 ios swift

我正在尝试构建一个简单的笔记应用程序。目前,我关注的是使用不同文本样式设置文本的可能性(例如正文、标题、粗体、斜体等)。我用 aNSAttributedString来设置不同的文本样式。现在,我想检测所选文本应用了哪种样式。

我认为一个好方法是创建一个自定义 NSAttributedString。Key,以便我可以在设置属性时分配它(例如.textStyle: "headline",并在需要检测它时读取它。我尝试将其实现为 NSAttributedString.Key 的扩展,但没有成功。正确的方法是什么?有更好的选择吗?

Leo*_*bus 6

您可以简单地创建一个 TextStyle 枚举并设置您的案例“正文、标题、粗体、斜体等”(如果需要,您可以为它们分配任何值)。然后你只需要创建一个新的 NSAttributedString 键:


enum TextStyle {
    case body, headline, bold, italic
}
Run Code Online (Sandbox Code Playgroud)
extension NSAttributedString.Key {
    static let textStyle: NSAttributedString.Key = .init("textStyle")
}
Run Code Online (Sandbox Code Playgroud)

游乐场测试

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))
}
Run Code Online (Sandbox Code Playgroud)