10

这一定是一件容易的事,但我无法弄清楚。

我有一个 NSMutableAttributedString,例如,“这是一个测试”。我想把“测试”这个词染成蓝色,我这样做:

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”一词之后输入仍然是蓝色的。

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

为任何输入欢呼。

4

2 回答 2

7

万一其他人偶然发现了这一点,我想发布我用来解决问题的代码。我最终使用了卡米尔的建议并添加:

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;
    }

到文本更改处理程序。

于 2013-10-01T18:57:38.120 回答
1

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

于 2013-10-01T18:44:40.267 回答