比如文本展示爲姓名和性別,但是我們不能排除姓名會很長,所以此刻的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: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]
簡單就先介紹我常用的這幾種