ios - NSAttributedString 在字符串末尾更改颜色

标签 ios colors nsattributedstring

这一定很容易做到,但我想不通。

我有一个 NSMutableAttributedString,其中包含例如“这是一个测试”。我想将“test”这个词涂成蓝色,我这样做是这样的:

NSMutableAttributedString *coloredText = [[NSMutableAttributedString alloc] initWithString:@"This is a test"];

[coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(10,4)];

这很好用。但现在我想将“测试”后键入的任何内容的文本颜色设置回黑色。

如果我这样做:

[coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(coloredText.string.length, 1)];

我收到 objectAtIndex:effectiveRange: out of bounds 错误。推测是因为范围超出了字符串的长度。

如果我这样做:

[coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(coloredText.string.length, 0)];

错误消失了,但是在“test”这个词之后输入仍然是蓝色的。

当插入点位于字符串末尾时,如何设置插入点的当前颜色?

欢迎任何输入。

最佳答案

如果其他人偶然发现了这个问题,我想发布我用来解决问题的代码。我最终使用了 Kamil 的建议并添加了:

NSAttributedString *selectedString = [textView.attributedText attributedSubstringFromRange:NSMakeRange(textView.attributedText.string.length - 1, 1)];
    __block BOOL isBlue = NO;

    [selectedString enumerateAttributesInRange:NSMakeRange(0, [selectedString length]) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop) {
        isBlue = [[attributes objectForKey:NSForegroundColorAttributeName] isEqual:[UIColor blueColor]];
    }];

    if (isBlue) {
        NSMutableAttributedString *coloredText = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
        [coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(textView.attributedText.string.length - 1, 1)];
        textView.attributedText = coloredText;
    }

到文本更改处理程序。

关于ios - NSAttributedString 在字符串末尾更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123503/

相关文章:

ios - physicsbody.dynamic 和 physicsbody.categorybitmask 之间有什么关系

ios - 使用Twitter SDK发送推文失败,但我不知道为什么

ios - Realm 结果数组的计数始终等于 1

ios - NSMutableAttributedString 在特定范围的 tableviewcell 中不起作用

objective-c - 将 NSAttributedString 转换为字符串并返回

ios - 带有 UIFontWeightTraits 的 NSAttributedString

ios - 在 PageTabViewStyle (SwiftUI 2.0) 或 PageViewController/PageView (带有 UIKit 界面) 上显示部分上一个和下一个项目

c# - Windows 窗体 - 非事件突出显示颜色

c# - 生成指定数量的随机但独特的颜色

javascript - 如何在 CKEditor 中用颜色填充整个单元格