我有 HTML 字符串,我在 UITextView
中显示为 NSAttributedString
。现在我想根据某些条件在属性字符串中插入/替换字符串。
- 属性字符串本身有多个部分,我需要在特定部分插入一个字符串。
- 主要是识别部分,因为它可能位于字符串中的任何位置。
- 需要相对于其附近的相邻部分来识别部分。
我已经完成了剩余的工作,我可以用自定义的新字符串替换 NSAttributedString
中的部分字符串。我只需要字符串部分识别想法。
这是属性文本的屏幕截图
现在您可以看到关节 (R)、跖趾 (R) 和关节 (L) 三个部分。它们总是随机的,而不是在特定位置。
它们中的数据是有序的,但它可能有更多的小节。
现在,如果我想要 Metatarsophalangeal 部分内的所有字符串,我该如何获取它?
最佳答案
可以在字符串中设置任意属性。例如 [string setAttributes:@{ @"my custom attribute name": @(YES), ...} range:range];
然后,当你想再次使用那些属性时,你可以使用enumerateAttribute:
。注意使用 options:NSAttributedStringEnumerationReverse
来避免覆盖 copyOfString 中的数据。
[string enumerateAttribute:@"my custom attribute name" inRange:NSMakeRange(0, string.length) options:NSAttributedStringEnumerationReverse usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value){ // Do something here
[copyOfString replaceCharactersInRange:range withString:@"______"];
}
}];
关于ios - 在复杂的 NSAttributedString 中插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42619522/