为NSAttributedstring的不同部分应用不同的属性 [英] Applying different attributes for different portions of an NSAttributedstring

查看:119
本文介绍了为NSAttributedstring的不同部分应用不同的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以将属性应用于NSAttributedString。



但是我们如何将不同的属性应用于相同的属性字符串。



字符串这是一个属性文本。



我们如何将特定属性(背景颜色或前景色)设置为This是
另一个属性(背景颜色或前景色)到属性文本。



有没有办法实现这个目的....? / p>

还有什么方法可以在iOS中设置NSAttributedString的背景颜色吗?

解决方案

制作属性字符串的可变副本,然后使用:



-setAttributes:range:

-addAttributes:range :

-addAttribute:value:range:

-removeAttributes:range:



例如,设置红色对于前四个字母:

  NSMutableAttributedString * mutAttrStr = [attributedString mut ableCopy]; 
CGColorRef redClr = [UIColor redColor] .CGColor;
NSDictionary * newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0,4)];

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/参考/ Reference.html



在iOS上没有内置的方法来绘制背景颜色。您可以为属性创建自定义字符串常量,例如MyBackgroundColorAttributeName,然后您必须自己绘制它。


I know it is possible to apply attributes to an NSAttributedString.

But how can we apply different attributes to same attributed string.

for the string "This is an attributed text."

How can we set a particular attribute(background color or foreground color) to "This is" another attribute(background color or foreground color) to "an attributed text."

Is there any way to achieve this....?

Also is there any way to set the background color of an NSAttributedString in iOS?

解决方案

Make a mutable copy of the attributed string, and then use either:

-setAttributes:range:
-addAttributes:range:
-addAttribute:value:range:
-removeAttributes:range:

for example, to set a red color for the first four letters:

NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy];
CGColorRef redClr = [UIColor redColor].CGColor;
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)];

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html

There's no built-in way to draw the background color on iOS. You can create a custom string constant for the attribute, eg "MyBackgroundColorAttributeName", and then you'll have to draw it yourself.

这篇关于为NSAttributedstring的不同部分应用不同的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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