NSAttributedString改变字符串结尾处的颜色 [英] NSAttributedString change color at end of string

查看:267
本文介绍了NSAttributedString改变字符串结尾处的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个NSMutableAttributedString,例如,这是一个测试,这是一个很容易的事情,但我不能弄清楚。在里面。我想对test蓝色进行着色,我这样做:

  NSMutableAttributedString * coloredText = [[NSMutableAttributedString alloc] initWithString:@这是一个测试]; 

[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 error。假定因为范围超出字符串的长度。



如果我这样做:

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

错误消失,但在test一词后输入蓝色。



如果在字符串结尾处的插入点处设置当前颜色



为任何输入。

解决方案

如果文本更改,您需要重新计算属性,因为它们的有效范围不会随着文本。


This must be an easy thing to do, but I cannot figure it out.

I have a NSMutableAttributedString that has, for example, "This is a test" in it. I want to color the word "test" blue, which I do with this:

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

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

That works just fine. But now I want to set the text color back to black for anything typed after "test".

If I do:

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

I get an objectAtIndex:effectiveRange: out of bounds error. Assumedly because the range extends beyond the length of the string.

If I do:

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

The error goes away but typing after the word "test" remains blue.

How do I set the current color at the insertion point when it is at the end of the string??

Cheers for any input.

解决方案

You need to recalculate the attributes if the text changes, because their effective range doesn't automatically change with the length of text.

这篇关于NSAttributedString改变字符串结尾处的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆