NSAttributedString能让UILable的文字有不同的颜色、字体等,可以实现搜索时关键字的高亮状态。
.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];
//设置文本格式
//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];
}
网友评论