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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With