james VB
james VB

Reputation: 31

How can I add a custom view to an attributed string or text view?

I'm trying to get a custom view in an attributed string to be displayed on a textView. I am able to add an image with an NSTextAttachment, but it isn't what I want. I have a custom view that supports Gif's and Animated PNGs that I'd like to display between text.

Example:

text text text [customView] text [customView] text. <- In text view, preferably in attributed string

I would love some guidance as to where I should search specifically. So far I've seen related issues...

Upvotes: 3

Views: 5080

Answers (1)

L.wind
L.wind

Reputation: 57

First, use NSAttributedString or NSMutableAttributedString to show your RichText in subviews (such as UITextView/UILabel)

Then, use NSTextAttachment to replace your image-script in text.

NSString *egText = @"hello [this_is_an_img_script]";

NSMutableAttributedString * destStr = [[NSMutableAttributedString alloc] initWithString:egText];

NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];

attachment.image = [UIImage imageNamed:[this_is_an_img_script]];

NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; //make your image to an attributedString

[destStr replaceCharactersInRange:range withAttributedString:textAttachmentString];

at last: [YourLabel(or YourTextView) setAttributedString:destStr];

BTW: if you use the YYkit for the RichText, you cannot use the YYAttachMentString to replace NSAttachMentString, these are different things, the UITextView(UILabel) cannot load the YYAttachMentString. I'm looking for some way to show my gifs with the UITextView (because YYKit cannot load and preview netimage with a url, YYKit always show empty which should be a netImage, cripes!)

Upvotes: 0

Related Questions