I am trying to get the following effect using a UITextView:
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).
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];
@bilobatum's code converted to Swift for those in need:
let attributedString = NSMutableAttributedString(string: "like after")
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(named: "whatever.png")
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: NSMakeRange(4, 1), with: attrStringWithImage)
You could try using NSAttributedString and NSTextAttachment. Take a look at the following link for more details on customising the NSTextAttachment in order to resize the image. http://ossh.com.au/design-and-technology/software-development/implementing-rich-text-with-images-on-os-x-and-ios/
In my example I resize the image to fit the width, in your case you may want to resize the image to match the line height.
Problem solution in simple example is
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "qrcode")
let firstString = NSMutableAttributedString(string: "scan the ")
let iconString = NSAttributedString(attachment: attachment)
let secondString = NSAttributedString(string: "QR code received on your phone.")
firstString.append(iconString)
firstString.append(secondString)
self.textLabel.attributedText = firstString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With