美文网首页
iOS开发--NSAttributedString

iOS开发--NSAttributedString

作者: XDRS潇潇雨歇 | 来源:发表于2016-02-20 00:35 被阅读0次

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];

}

相关文章

网友评论

      本文标题:iOS开发--NSAttributedString

      本文链接:https://www.haomeiwen.com/subject/cfsvkttx.html