在開發(fā)中,會遇到一段文本顯示成不同屬性或者在文字中間插入一些表情,圖片,鏈接等情況.實(shí)現(xiàn)方法有很多,但是效果都不太理想.發(fā)現(xiàn)NSMuttableAttstring(富文本)可以很簡單實(shí)現(xiàn)以上需求.
NSMuttableAttstring的三種初始化方法與區(qū)別####
方法1:######
//創(chuàng)建富文本方法1
NSMutableAttributedString *attrStr1 = [[NSMutableAttributedString alloc] initWithString:@"這是一個富文本字符串1"];
方法1富文本效果
方法2:######
//設(shè)置文本屬性
NSDictionary *attributesDic = @{NSFontAttributeName:[UIFont systemFontOfSize:22],NSForegroundColorAttributeName:[UIColor redColor]};
//創(chuàng)建富文本方法2
NSMutableAttributedString *attrStr2 = [[NSMutableAttributedString alloc] initWithString:@"這是一個富文本字符串2" attributes:attributesDic];
方法2可以對文字添加屬性
方法3:######
//創(chuàng)建富文本方法3
NSMutableAttributedString *attrStr3 = [[NSMutableAttributedString alloc] initWithAttributedString:attrStr2];
方法3通過attrStr2創(chuàng)建,與富文本2是一樣的效果
NSMuttableAttstring的屬性添加####
core API: addAttribute:參數(shù)1 value:參數(shù)2 range:參數(shù)3
參數(shù)1:設(shè)置的屬性類型
參數(shù)2:設(shè)置屬性值
參數(shù)3:設(shè)置屬性的文本范圍
可設(shè)置的文本屬性很多,在這里就不一一演示,拿出實(shí)用的幾個來看下效果,如果想查看可文本屬性可以參考詳解文本屬性Attributes.
//字體顏色設(shè)置
[attrStr2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 3)];
指定文本顏色設(shè)置
//下劃線設(shè)置(下劃線類型很多,可以根據(jù)需求選擇)
[attrStr2 addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(5, 3)];
指定文字下劃線設(shè)置
//超鏈接設(shè)置
[attrStr2 addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"http://www.reibang.com/p/012dd4027d5c"] range:NSMakeRange(5, 3)];
注意的是超鏈接文本需要把 textView的editable 屬性設(shè)置為 NO才可以進(jìn)行超鏈接(UILabel, UITextField 不好用);
點(diǎn)擊指定文本進(jìn)行跳轉(zhuǎn)
//設(shè)置文字陰影
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowOffset = CGSizeMake(2, 2);
shadow.shadowBlurRadius = 1.5;
shadow.shadowColor = [UIColor grayColor];
[attrStr2 addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(5, 3)];
指定文字陰影
//圖文混排
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"IMG_4802.png"];
textAttachment.bounds = CGRectMake(0, -5, 30, 30);
// 用textAttachment生成屬性字符串
NSAttributedString *attachmentAttrStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
// 屬性字符串插入到目標(biāo)字符串
[attrStr2 insertAttributedString:attachmentAttrStr atIndex:8];
圖文混排