这一定很容易做到,但我想不通。
我有一个 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/