最近碰到了一个关于用一个label显示换行与文字多中颜色显示的问题,本人第一想到的就是富文本NSAttributedString,试过之后发现效果还不错.
NSAttributedString叫作富文本,是一种带有属性的字符串,可对字符串进行多种修改,可改变文字的font、color、下划线。。。
self.label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 0, 0)];
NSString *str = @"竹外桃花三两枝,\n春江水暖鸭先知。\n萎蒿满地芦芽短,\n正是河豚欲上时。";
NSRange rang = [str rangeOfString:@"春江水暖鸭先知。"];
NSRange rang1 = [str rangeOfString:@"萎蒿满地芦芽短,"];
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(0, 7)];
//添加颜色
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:rang];
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor cyanColor] range:rang1];
//添加下划线
[attrStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(9, 7)];
self.label.backgroundColor = [UIColor whiteColor];
self.label.numberOfLines = 0;
self.label.attributedText = attrStr;
[self.label sizeToFit];
//添加阴影
self.label.shadowColor = [UIColor redColor];
self.label.shadowOffset = CGSizeMake(1.5, 1.5);
显示效果如下: