iOS 7 TextKit - How to insert images inline with text?

Andy Hin picture Andy Hin · Jan 5, 2014 · Viewed 58.2k times · Source

I am trying to get the following effect using a UITextView:

enter image description here

Basically I want to insert an image between text. The image can simply just take up 1 row of space so there is no wrapping necessary.

I tried just adding a UIView to the subview:

UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[pictureView setBackgroundColor:[UIColor redColor]];
[self.textView addSubview:pictureView];

But it seems to float over the text and cover it.

I did a bit of reading on exclusion paths which appears to be one way of implementing this. However, I don't want to absolutely position the image - instead, it should flow with the text (similar to how <span> behaves in HTML).

Answer

bilobatum picture bilobatum · Jan 5, 2014

You'll need to use an attributed string and add the image as instance of NSTextAttachment:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"like after"];

NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"whatever.png"];

NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];

[attributedString replaceCharactersInRange:NSMakeRange(4, 1) withAttributedString:attrStringWithImage];