
前一陣子在做項(xiàng)目的時(shí)候涉及到了圖文混排的內(nèi)容,用的是
NSMutableAttributedString,今天正好整理下,以便日后查閱
先來(lái)看一個(gè)小例子,實(shí)現(xiàn)表情圖片和文字的混排效果,這里我們用Swift來(lái)實(shí)現(xiàn):
class ViewController: UIViewController {
@IBOutlet weak var demoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let attrStr = NSAttributedString(string: "歡迎再次回來(lái):", attributes: [NSForegroundColorAttributeName : UIColor.red])
let attrStr1 = NSAttributedString(string: "Adinm", attributes: [NSForegroundColorAttributeName : UIColor.blue])
// 圖文混排
let attacment = NSTextAttachment()
attacment.image = UIImage(named: "d_aini")
// 獲取文字字體
let font = demoLabel.font
attacment.bounds = CGRect(x: 0, y: -4, width: (font?.lineHeight)!, height: (font?.lineHeight)!)
let attrImageStr = NSAttributedString(attachment: attacment)
let attrMStr = NSMutableAttributedString()
attrMStr.append(attrStr)
attrMStr.append(attrImageStr)
attrMStr.append(attrStr1)
demoLabel.attributedText = attrMStr
}
}

圖文混排.png
通過(guò)上面的代碼我們可以看到通過(guò)NSTextAttachment可以將圖片以附件的形式插入到屬性文字中來(lái)達(dá)到我們想要的效果;
下面我們通過(guò)OC在來(lái)實(shí)現(xiàn)一遍:
NSString *str =@"歡迎再次回來(lái):Admin";
// 創(chuàng)建一個(gè)帶有屬性的字符串(比如顏色屬性、字體屬性等文字屬性)
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
// addAttribute:添加某一個(gè)具體屬性,添加一條刪除線(xiàn);
[attrStr addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleDouble) range:[str rangeOfString:@"Admin"]];
//addAttributes:添加多個(gè)屬性
NSMutableDictionary * dic=[NSMutableDictionary dictionary];
dic[NSFontAttributeName]=[UIFont boldSystemFontOfSize:26];
dic[NSForegroundColorAttributeName]=[UIColor redColor];
[attrStr addAttributes:dic range:[str rangeOfString:@"Admin"]];
self.lblTitle.attributedText = attrStr;

2.png
NSMutableAttributedString常見(jiàn)方法
為某一范圍內(nèi)文字設(shè)置多個(gè)屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
為某一范圍內(nèi)文字添加某個(gè)屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
為某一范圍內(nèi)文字添加多個(gè)屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某范圍內(nèi)的某個(gè)屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
常見(jiàn)的屬性及說(shuō)明
NSFontAttributeName 字體
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字體顏色
NSBackgroundColorAttributeName 背景顏色
NSStrikethroughStyleAttributeName 刪除線(xiàn)格式
NSUnderlineStyleAttributeName 下劃線(xiàn)格式
NSStrokeColorAttributeName 刪除線(xiàn)顏色
NSStrokeWidthAttributeName 刪除線(xiàn)寬度
NSShadowAttributeName 陰影