![](/img/trans.png)
[英]Add UITextView and UIImageView under UITableViewCell programmatically Swift 4
[英]Add UIImageview in Uitextview as in iMessage
我正在使用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 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;
那是一個小的內聯圖像。 聽起來您想在自己的段落中添加圖像,但是原理是完全一樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.