在實(shí)際項(xiàng)目開發(fā)過程中扼睬,我們常會(huì)遇到一段文字中既要有圖片又要有文字屯耸,例如下圖是我實(shí)際需要的效果是這樣:
后來看到一大神的博客护锤,學(xué)習(xí)參考了一下裆操,最后做出來效果了:
步驟一:
NSMutableAttributedString創(chuàng)建一個(gè)富文本對(duì)象怒详,調(diào)用富文本的對(duì)象方法addAttribute:(NSString * )value:(id) range:(NSRange)來修改對(duì)應(yīng)range范圍中 attribute屬性的 value值,但是我這里不需要踪区,直接創(chuàng)建富文本對(duì)象就行了:
1.NSMutableAttributedString *attri =? ? [[NSMutableAttributedString alloc] initWithString:@"(完善訂單信息昆烁,兌換禮品 ,請(qǐng)聯(lián)系農(nóng)商友現(xiàn)場(chǎng)服務(wù)人員)"];
步驟二:
我需要在禮品后插入圖片缎岗,計(jì)算好插入的index位置是多少
1.創(chuàng)建NSTextAttachment的對(duì)象静尼,用來裝在圖片
將NSTextAttachment對(duì)象的image屬性設(shè)置為想要使用的圖片
設(shè)置NSTextAttachment對(duì)象bounds大小,也就是要顯示的圖片的大小
NSTextAttachment *attch = [[NSTextAttachment alloc] init];
attch.image = [UIImage imageNamed:@"icon_bill_gift"];
attch.bounds = CGRectMake(0, 0, 14.5, 16);
2.用[NSAttributedString attributedStringWithAttachment:attch]方法传泊,將圖片添加到富文本上
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attri insertAttributedString:string atIndex:13];
mayLabel.attributedText = atria;
這樣就完成了鼠渺。
可以參考的原文鏈接:http://www.reibang.com/p/5828173adc3a