问题
I am using UItextview
and adding an extra inputAccessoryview
for toolbar buttons to perform additional actions.
My toolbar has a camera icon which gets the image from UIImagePickerController
and Ι have to add this image in my UItextview
.
Right now Ι am able to do this with :
[myTextView addSubView:imageView];
But that way, always adds the image at the beginning of the textview and what Ι want is to add it at the current cursor location. I would also like to remove this image just like I remove the text from textview.
Just for the record, Ι also tried getting UItextview
text's selected range and tried inserting my imageview
at that location but it did not work.
Edited Code:
NSMutableAttributedString * mas = [[NSMutableAttributedString alloc]initWithString:self.commentsTextView.text];
NSRange cursorPoistion = [self.commentsTextView selectedRange];
UIImage *chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
NSTextAttachment* onionatt = [NSTextAttachment new];
onionatt.image = chosenImage;
onionatt.bounds = CGRectMake(0,-5,200,200);
NSAttributedString* onionattchar = [NSAttributedString attributedStringWithAttachment:onionatt];
[mas insertAttributedString:onionattchar atIndex:(cursorPoistion.location + cursorPoistion.length)];
self.commentsTextView.attributedText = mas;
回答1:
This was impossible before iOS 7. Now, in iOS 7, you can do it because UITextView is based on Text Kit and inline images are possible in an NSAttributedString.
Here's a very simple example where I add a picture of onions just after the word "Onions" in my text (mas
is my NSMutableAttributedString):
UIImage* onions = [self thumbnailOfImageWithName:@"onion" extension:@"jpg"];
NSTextAttachment* onionatt = [NSTextAttachment new];
onionatt.image = onions;
onionatt.bounds = CGRectMake(0,-5,onions.size.width,onions.size.height);
NSAttributedString* onionattchar = [NSAttributedString attributedStringWithAttachment:onionatt];
NSRange r = [[mas string] rangeOfString:@"Onions"];
[mas insertAttributedString:onionattchar atIndex:(r.location + r.length)];
self.tv.attributedText = mas;
That's for a small inline image. It sounds like you want to add your image in a paragraph of its own, but the principle is exactly the same.
来源:https://stackoverflow.com/questions/22704292/add-uiimageview-in-uitextview-as-in-imessage