在實(shí)際項(xiàng)目開發(fā)過程中,我們常會遇到一段文字中既要有圖片又要有文字,例如下圖是我實(shí)際需要的效果是這樣:

后來看到一大神的博客,學(xué)習(xí)參考了一下,最后做出來效果了:

步驟一:
NSMutableAttributedString創(chuàng)建一個(gè)富文本對象,調(diào)用富文本的對象方法addAttribute:(NSString * )value:(id) range:(NSRange)來修改對應(yīng)range范圍中 attribute屬性的 value值,但是我這里不需要,直接創(chuàng)建富文本對象就行了:
1.NSMutableAttributedString *attri =? ? [[NSMutableAttributedString alloc] initWithString:@"(完善訂單信息,兌換禮品 ,請聯(lián)系農(nóng)商友現(xiàn)場服務(wù)人員)"];
步驟二:
我需要在禮品后插入圖片,計(jì)算好插入的index位置是多少
1.創(chuàng)建NSTextAttachment的對象,用來裝在圖片
將NSTextAttachment對象的image屬性設(shè)置為想要使用的圖片
設(shè)置NSTextAttachment對象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.itdecent.cn/p/5828173adc3a