首页 > 代码库 > UILable显示不同的字体颜色、字体大小、行间距、首行缩进、下划线等属性(NSMutableAttributedString)
UILable显示不同的字体颜色、字体大小、行间距、首行缩进、下划线等属性(NSMutableAttributedString)
案例1:修改文本字体大小、颜色属性
比如文本展示为姓名和性别,但是我们不能排除姓名会很长,所以此刻的lable宽度我们就不能写死,换句话说lable的宽度根据文本的内容来定
我经常用两种方式解决:
1.前面文章已经涉及:lable自适应http://blog.csdn.net/tuwanli125/article/details/51003798
2.就是使用NSMutableAttributedString属性给infoL设置文本
NSString *infoStr = [NSStringstringWithFormat:@"%@ %@",name,sex];
NSMutableAttributedString *infoAttStr = [[NSMutableAttributedStringalloc] initWithString:infoStr];
NSArray *colorArr =@[[UIColorcolorWithRed:0/255.0green:168/255.0blue:255/255.0alpha:1.0],[UIColorcolorWithRed:153/255.0green:153/255.0blue:153/255.0alpha:1.0]];
--------修改姓名的颜色,字体大小------
[infoAttStr addAttribute:NSForegroundColorAttributeNamevalue:colorArr[0]range:NSMakeRange(0,name.length)];
[infoAttStr addAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:15]range:NSMakeRange(0,name.length)];
--------修改性别的颜色,字体大小------
[infoAttStr addAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:12]range:NSMakeRange(name.length+1,sexStr.length)];
[infoAttStr addAttribute:NSForegroundColorAttributeNamevalue:colorArr[1]range:NSMakeRange(name.length+1,sexStr.length)];
[self.infoL setAttributedText:infoAttStr];
这样一个文本就可以了,简单快捷
案例2:文本行间距
remindLabel.text = @""(一堆文字,此处省略一万字)
NSMutableAttributedString *attributedString = [[NSMutableAttributedStringalloc]initWithString:remindLabel.text];;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc]init];
[paragraphStyle setLineSpacing:9];
paragraphStyle.maximumLineHeight = 60; //最大的行高
[paragraphStyle setFirstLineHeadIndent:30];//首行缩进
[attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStylerange:NSMakeRange(0, remindLabel.text.length)];
remindLabel.attributedText = attributedString;
案例3:添加下划线
我给按钮添加下滑线,比如按钮显示文本为电话号码,点击就可以拨打电话
NSMutableAttributedString *str = [[NSMutableAttributedStringalloc]initWithString:_phoneBtn.titleLabel.text];
NSRange strRange = {0,[strlength]};
[str addAttribute:NSUnderlineStyleAttributeNamevalue:[NSNumbernumberWithInteger:NSUnderlineStyleSingle]range:strRange];
[_phoneBtnsetAttributedTitle:strforState:UIControlStateNormal]
UILable显示不同的字体颜色、字体大小、行间距、首行缩进、下划线等属性(NSMutableAttributedString)