NSAttributedString在字符串末尾更改颜色

Rac*_*eur 9 colors nsattributedstring ios

这一定是件容易的事,但我无法理解.

我有一个NSMutableAttributedString,例如,"这是一个测试".我想给"测试"蓝色这个词加上颜色,我这样做:

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

[coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(10,4)];
Run Code Online (Sandbox Code Playgroud)

这很好用.但是现在我想将"测试"后输入的任何内容的文本颜色设置为黑色.

如果我做:

[coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(coloredText.string.length, 1)];
Run Code Online (Sandbox Code Playgroud)

我得到一个objectAtIndex:effectiveRange:越界错误.假设因为范围超出了字符串的长度.

如果我做:

[coloredText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(coloredText.string.length, 0)];
Run Code Online (Sandbox Code Playgroud)

错误消失但在"test"之后输入仍然是蓝色.

当它在字符串末尾时,如何在插入点设置当前颜色?

欢呼任何输入.

Rac*_*eur 6

如果其他人偶然发现了这个问题,我想发布用于解决问题的代码.我最后使用了卡米尔的建议,并补充说:

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

到文本改变处理程序.


kko*_*dev 1

如果文本发生变化,则需要重新计算属性,因为它们的有效范围不会随着文本长度自动变化。