【问题标题】:Add UIImageview in Uitextview as in iMessage像在 iMessage 中一样在 Uitextview 中添加 UIImageview
【发布时间】:2014-03-28 04:36:00
【问题描述】:

我正在使用UItextview 并为工具栏按钮添加额外的inputAccessoryview 以执行其他操作。 我的工具栏有一个相机图标,可以从UIImagePickerController 获取图像,我必须将此图像添加到我的UItextview

现在我能够做到这一点:

[myTextView addSubView:imageView];

但是那样,总是在文本视图的开头添加图像,我想要的是在当前光标位置添加它。我也想删除这张图片,就像我从 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;

【问题讨论】:

  • 你知道如何删除图像吗?

标签: ios objective-c uiimageview uitextview uiimagepickercontroller


【解决方案1】:

这在 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;

这是一个小的内联图像。听起来好像是想把自己的图片加到自己的段落里,但原理完全一样。

【讨论】:

  • 这更好,但它仍然不允许我添加多个图像。此外,当我添加下一张图片时,它会将文本推到左侧。当有图像时,我想要一个硬回报。请参阅上面的编辑以查看我正在使用的代码
猜你喜欢
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多