【问题标题】:NSAttributedString change color at end of stringNSAttributedString 在字符串末尾改变颜色
【发布时间】:2013-10-08 01:04:33
【问题描述】:

这一定是一件容易的事,但我想不通。

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

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

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

效果很好。但现在我想将“test”之后输入的任何内容的文本颜色设置回黑色。

如果我这样做:

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

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

欢迎任何意见。

【问题讨论】:

  • 您不能输入NSAttributedString。如果您使用UITextFieldUITextView,您应该正确更新您的问题。
  • 感谢您的评论,但这样做似乎有点谨慎,因为正如您所说,您不能输入 NSAttributedString,并且呈现字符串的控件与所提出的问题无关.

标签: ios colors nsattributedstring


【解决方案1】:

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

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

到文本更改处理程序。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 2012-02-03
      相关资源
      最近更新 更多