前段時(shí)間在做一個(gè)需求,大致是在一個(gè)Lable中顯示幾種不同字體和字號(hào)的文字击儡,起初我的想法是使用UILabel的textLayer來進(jìn)行重繪塔沃,但是操作起來太麻煩。所以放棄了這個(gè)方案阳谍,之后又咨詢了一位好朋友蛀柴,他給我的建議就是使用富文本,經(jīng)過了一番研究決定將學(xué)習(xí)到東西記錄下來分享給大家边坤。
NSMuttableAttstring
NSMuttableAttstring在NSAttributedString的基礎(chǔ)之上添加了2個(gè)主要方法名扛,一個(gè)是替換指定范圍字符的方法(下面成為方法一),另一個(gè)是設(shè)定指定范圍字符樣式的方法(下面成為方法二)茧痒。
方法一(替換指定范圍字符)
//1.實(shí)例化NSMutableAttributedString
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"天將降大任于斯人也,必先苦其心志肮韧,勞其筋骨,餓其體膚旺订。"];
//2.調(diào)用replaceCharactersInRange方法
//第一個(gè)參數(shù)確定替換位置
//第二個(gè)參數(shù)確定替換的文字
[AttributedStr replaceCharactersInRange:NSMakeRange(0, 5) withString:@"大牛弟弟"];
//3.給lable賦值弄企,目的是為了顯示
lable2.attributedText = AttributedStr;```
#####方法二(設(shè)定指定范圍字符樣式)
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"天將降大任于斯人也,必先苦其心志,勞其筋骨区拳,餓其體膚拘领。"];
[AttributedStr setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial-BoldMT" size:20]} range:NSMakeRange(0, 5)];
lable2.attributedText = AttributedStr;

是不是很簡單?其實(shí)使用方法并不是難點(diǎn)樱调,關(guān)鍵在于是否知道能使用的樣式都有哪些约素,下面在介紹一些常見樣式届良。
1. ```NSFontAttributeName :[UIFont fontWithName:@"Arial-BoldMT" size:20]```設(shè)置字體和字體大小
2. ```NSBackgroundColorAttributeName:[UIColor redColor]```設(shè)置容器的背景顏色
3. ```NSForegroundColorAttributeName:[UIColor blueColor]```設(shè)置文字的顏色
4. ```NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:1]```設(shè)置文字下劃線,接受NSNumber類型圣猎,0為無下劃線士葫,1為有下劃線
5. ```NSUnderlineColorAttributeName:[UIColor greenColor]```設(shè)置下?lián)Q線顏色
6. ```NSLinkAttributeName:[NSURL URLWithString:@"www.baidu.com"]```設(shè)定文字的超鏈接,如果需要跳轉(zhuǎn)送悔,只能使用UITextView配合代理實(shí)現(xiàn)慢显,UILable經(jīng)過測試無法實(shí)現(xiàn)這樣的功能。
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"天將降大任于斯人也,必先苦其心志欠啤,勞其筋骨荚藻,餓其體膚。"];
[AttributedStr setAttributes:@{
NSFontAttributeName:[UIFont fontWithName:@"Arial-BoldMT" size:20],
NSBackgroundColorAttributeName:[UIColor redColor],
NSForegroundColorAttributeName:[UIColor blueColor],
NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:1],
NSUnderlineColorAttributeName:[UIColor greenColor],
NSLinkAttributeName:[NSURL URLWithString:@"www.baidu.com"]
} range:NSMakeRange(0, 5)];
lable2.attributedText = AttributedStr;

關(guān)于文字樣式洁段,還有很多有意思的樣式這里不多介紹应狱,剩下的就等待有興趣的同學(xué)自己發(fā)掘啦