1.實(shí)例化方法和使用方法
實(shí)例化方法:
使用字符串初始化
- (id)initWithString:(NSString*)str;
例:
NSMutableAttributedString*AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"今天天氣不錯(cuò)呀"];
- (id)initWithString:(NSString*)str attributes:(NSDictionary*)attrs;
字典中存放一些屬性名和屬性值,如:
NSDictionary*attributeDict = [NSDictionarydictionaryWithObjectsAndKeys:
[UIFontsystemFontOfSize:15.0],NSFontAttributeName,
[UIColorredColor],NSForegroundColorAttributeName,
NSUnderlineStyleAttributeName,NSUnderlineStyleSingle,nil];
NSMutableAttributedString*AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"今天天氣不錯(cuò)呀"attributes:attributeDict];
- (id)initWithAttributedString:(NSAttributedString*)attester;
使用NSAttributedString初始化,跟NSMutableString,NSString類似
使用方法:
為某一范圍內(nèi)文字設(shè)置多個(gè)屬性
- (void)setAttributes:(NSDictionary*)attrs range:(NSRange)range;
為某一范圍內(nèi)文字添加某個(gè)屬性
- (void)addAttribute:(NSString*)name value:(id)value range:(NSRange)range;
為某一范圍內(nèi)文字添加多個(gè)屬性
- (void)addAttributes:(NSDictionary*)attrs range:(NSRange)range;
移除某范圍內(nèi)的某個(gè)屬性
- (void)removeAttribute:(NSString*)name range:(NSRange)range;
2.常見(jiàn)的屬性及說(shuō)明
NSFontAttributeName字體
NSParagraphStyleAttributeName段落格式
NSForegroundColorAttributeName字體顏色
NSBackgroundColorAttributeName背景顏色
NSStrikethroughStyleAttributeName刪除線格式
NSUnderlineStyleAttributeName下劃線格式
NSStrokeColorAttributeName刪除線顏色
NSStrokeWidthAttributeName刪除線寬度
NSShadowAttributeName陰影
更多方法和屬性說(shuō)明詳見(jiàn)蘋果官方說(shuō)明文檔:
3.使用實(shí)例
UILabel*testLabel=[[UILabelalloc]initWithFrame:CGRectMake(0,100,320,30)];
testLabel.backgroundColor=[UIColorlightGrayColor];
testLabel.textAlignment=NSTextAlignmentCenter;
NSMutableAttributedString*AttributedStr=[[NSMutableAttributedStringalloc]initWithString:@"今天天氣不錯(cuò)呀"];
[AttributedStraddAttribute:NSFontAttributeName
value:[UIFontsystemFontOfSize:16.0]
range:NSMakeRange(2,2)];
[AttributedStraddAttribute:NSForegroundColorAttributeName
value:[UIColorredColor]
range:NSMakeRange(2,2)];
testLabel.attributedText=AttributedStr;
[self.viewaddSubview:testLabel];
運(yùn)行效果:

另外,其他可以設(shè)置text的控件(如UIButton,UITextField)也都有該屬性,該文章不夠詳細(xì),只是簡(jiǎn)單介紹,其他效果的實(shí)現(xiàn)參考API中更多的屬性及使用方法。
轉(zhuǎn)載自:http://blog.csdn.net/reylen/article/details/41208747