ios - 在复杂的 NSAttributedString 中插入字符串

标签 ios objective-c swift nsattributedstring

我有 HTML 字符串,我在 UITextView 中显示为 NSAttributedString。现在我想根据某些条件在属性字符串中插入/替换字符串。

  • 属性字符串本身有多个部分,我需要在特定部分插入一个字符串。
  • 主要是识别部分,因为它可能位于字符串中的任何位置。
  • 需要相对于其附近的相邻部分来识别部分。

我已经完成了剩余的工作,我可以用自定义的新字符串替换 NSAttributedString 中的部分字符串。我只需要字符串部分识别想法。

这是属性文本的屏幕截图

enter image description here

现在您可以看到关节 (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/

相关文章:

ios - UIImagePickerController 不能在 Swift 中工作

ios - 如何禁用 MGLAnnotation 的用户交互?

iphone - 添加按钮到工具栏

iphone - 如何刷新 iPhone 的 UIWebview?

ios - NSString在时间之前释放

iphone - 用于在 Iphone sdk 中进行视频电话 session 的 API?

swift - 如何最初在导航栏中显示搜索栏,但在用户向上滚动时仍将其隐藏?

ios - 直接使用访问器的核心数据 NSTimeInterval 存在错误

iphone - iOS - 创建没有小时/分钟的 NSDate 并忽略夏令时类次

ios - 具有环绕但不滚动的 UIView 的水平列表