ios - 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?
解决方案
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))
}
推荐阅读
- intellij-idea - IntelliJ IDEA - 如何构建模块化 Kotlin 多平台项目 (Android/iOS)
- .net - 405(方法不允许)使用 Angular httpClient POST
- wcf - WCF 客户端。检查证书存储中的证书。这是确保只有某些客户端可以连接到服务的好方法吗?
- java - 在命令提示符下,能够从不同的目录编译 java 文件但不能运行它
- java - “找不到可接受的表示”406
- java - 如何使用java以不同的端口一一启动appium两次?
- javascript - 如何使用 MongoDB 获取给定日期范围的数据?
- oracle - OBIEE 是否支持 PostgreSQL 数据库作为数据源?
- python - 为什么在 datetime.time 毫秒字段中添加了三个额外的零?
- ruby-on-rails - 其他模型上完全相同的 Cocoon 形式发送其他参数