簡體   English   中英

如何檢測UITextView中的圖像刪除

[英]How to detect deletion of image in UITextView

如果我將圖像添加到UITextView中,如下所示:

NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = image;

NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[myString appendAttributedString:attrStringWithImage];

self.inputTextView.attributedText = myString;

之后如何通過用戶點擊鍵盤上的后退按鈕來檢測圖像是否已被刪除?

我會用下面的嗎?

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

如果是這樣,怎么樣?

我這樣做了:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
[self.textView.attributedText enumerateAttribute:NSAttachmentAttributeName
                        inRange:NSMakeRange(0, self.textView.attributedText.length)
                        options:0
                     usingBlock:^(id value, NSRange imageRange, BOOL *stop){
     if (NSEqualRanges(range, imageRange) && [text isEqualToString:@""]){
         //Wants to delete attached image
     }else{
         //Wants to delete text
     }

  }];
return YES;
}

希望,能幫到你!

使用swift,這是我從UITextView中刪除圖像(添加為NSTextAttachment)的方法:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    // empty text means backspace
    if text.isEmpty {
        textView.attributedText.enumerateAttribute(NSAttachmentAttributeName, inRange: NSMakeRange(0, textView.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { [weak self] (object, imageRange, stop) in

            if NSEqualRanges(range, imageRange) {
                self?.attributedText.replaceCharactersInRange(imageRange, withString: "")
            }
        }
    }

    return true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM