问题描述
我正在使用 UItextview
并为工具栏按钮添加一个额外的 inputAccessoryview
以执行其他操作.我的工具栏有一个相机图标,它从 UIImagePickerController
获取图像,我必须将此图像添加到我的 UItextview
中.
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];
但是那样,总是在文本视图的开头添加图像,我想要的是将它添加到当前光标位置.我也想删除这张图片,就像我从 textview 中删除文本一样.
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.
为了记录,我还尝试获取 UItextview
文本的选定范围并尝试在该位置插入我的 imageview
但它不起作用.
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.
编辑代码:
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;
推荐答案
这在 iOS 7 之前是不可能的.现在,在 iOS 7 中,您可以做到这一点,因为 UITextView 是基于 Text Kit 的,并且内联图像可以在 NSAttributedString 中.
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.
这是一个非常简单的示例,我在文本中的洋葱"一词之后添加了一张洋葱图片(mas
是我的 NSMutableAttributedString):
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.
这篇关于像在 iMessage 中一样在 Uitextview 中添加 UIImageview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!