UILable顯示不同的字型顏色、字型大小、行間距、首行縮排、下劃線等屬性(NSMutableAttributedString)
比如文字展示為姓名和性別,但是我們不能排除姓名會很長,所以此刻的lable寬度我們就不能寫死,換句話說lable的寬度根據文字的內容來定
我經常用兩種方式解決:
2.就是使用NSMutableAttributedString屬性給infoL設定文字
NSString *infoStr = [NSStringstringWithFormat:@"%@ %@",name,sex];
NSMutableAttributedString *infoAttStr = [[NSMutableAttributedStringalloc] initWithString
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
--------修改性別的顏色,字型大小------
[infoAttStr addAttribute:NSFontAttributeNamevalue:[UIFontsystemFontOfSize:12]range:NSMakeRange(name.length+1,sexStr.length)];
[infoAttStr addAttribute:NSForegroundColorAttributeName
[self.infoLsetAttributedText: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:paragraphStyle range: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:str forState:UIControlStateNormal]
簡單就先介紹我常用的這幾種