像在iMessage中一样在Uitextview中添加UIImageview

Ash*_*osh 1 objective-c uitextview uiimageview uiimagepickercontroller ios

我正在使用UItextview并添加额外inputAccessoryview的工具栏按钮来执行其他操作.我的工具栏有一个摄像头图标,可以从中获取图像,UIImagePickerController并且必须在我的图像中添加此图像UItextview.

现在我能够做到这一点:

[myTextView addSubView:imageView];
Run Code Online (Sandbox Code Playgroud)

但是这样,总是在textview的开头添加图像,并且想要将其添加到当前光标位置.我也想删除此图像,就像我从textview中删除文本一样.

只是为了记录,Ι也尝试获取UItextview文本的选定范围,并尝试imageview在该位置插入我,但它不起作用.

编辑代码:

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;
Run Code Online (Sandbox Code Playgroud)

mat*_*att 8

在iOS 7之前这是不可能的.现在,在iOS 7中,您可以这样做,因为UITextView基于Text Kit,并且NSAttributedString中可以使用内嵌图像.

这是一个非常简单的例子,我在文本中添加了洋葱图片(mas就是我的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;
Run Code Online (Sandbox Code Playgroud)

这是一个小的内嵌图像.听起来你想在自己的段落中添加你的图像,但原理完全相同.