How to detect deletion of image in UITextView
Asked Answered
W

2

6

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?

Wildfire answered 10/4, 2015 at 22:34 Comment(0)
T
3

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!

Triable answered 27/10, 2015 at 19:7 Comment(0)
T
1

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
}
Tolentino answered 29/3, 2016 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.