简体   繁体   中英

How to detect deletion of image in UITextView

If I add an image into a UITextView like this:

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

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

self.inputTextView.attributedText = myString;

How can I then later detect that the image has been deleted via the user hitting the back button on the keyboard?

Would I use the below?

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

If so, how?

I did this:

- (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;
}

Hope, can help you!

Using swift, here's how I removed images (added as NSTextAttachment) from UITextView:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM