NSAttributedString能讓UILable的文字有不同的顏色讼庇、字體等想邦,可以實(shí)現(xiàn)搜索時(shí)關(guān)鍵字的高亮狀態(tài)峡捡。
.m文件:
#import"RootViewController.h"
@interfaceRootViewController()
@end
@implementationRootViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
NSString*str =@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈\n哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈";
UILabel*lable = [[UILabelalloc]initWithFrame:self.view.frame];
NSMutableAttributedString*string = [[NSMutableAttributedStringalloc]initWithString:str];
//設(shè)置文本格式
//1.字體色
[stringaddAttribute:NSForegroundColorAttributeNamevalue:[UIColororangeColor]range:NSMakeRange(0,2)];
//字大小
[stringaddAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:9]range:NSMakeRange(0,2)];
//3.背景色
[stringaddAttribute:NSBackgroundColorAttributeNamevalue:[UIColorpurpleColor]range:NSMakeRange(0, str.length)];
//段落格式
NSMutableParagraphStyle*style = [[NSMutableParagraphStylealloc]init];
style.lineSpacing=9;
style.paragraphSpacing=20;
[stringaddAttribute:NSParagraphStyleAttributeNamevalue:stylerange:NSMakeRange(0, str.length)];
lable.numberOfLines=0;
lable.attributedText= string;
[self.viewaddSubview:lable];
[lablerelease];
}