Add attachment image to attributed string in iOS 6

Fuli picture Fuli · Apr 13, 2014 · Viewed 10.2k times · Source

I have spent 3 hours on this but just can't solve it, anybody knows why? please help me!

The code below added an image as an attachment to an attributed string,

UIImage *img = [UIImage imageNamed:imgName];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = img;
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] init];
[attrStr appendAttributedString:attrStringWithImage];

Then I assigned attrStr to a UITextView's attributedText, this works great in iOS 7 but in iOS 6 the image is not displayed, I heard attributedText is supported for UITextView since iOS 6, is there anything different should I do for iOS 6?

PS: in iOS 6, if I assign attrStr to UILabel's attributedText, it is displayed, what's the special for UITextView?

Answer

Ting Wu picture Ting Wu · Oct 31, 2014

+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment is available in iOS 7.0 and later. So in iOS 6 and earlier version of iOS, you may use UIWebView or third library to display image in a Label or TextView.