Search code examples
iosuitextviewnstextattachment

Delete / Remove NSTextAttachment from UITextView


I have a UITextView that will have a mixture of images (as NSTextAttachment) and character strings. The UITextView is NOT selectable, so I can use:

- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange 

How do I delete the textAttachment in the method?


Solution

  • You can use replaceCharactersInRange:withString: of NSMutableAttributedString to remove the attachement (you got the range as parameter of the UITextViewDelegate method):

    //Retrieve the attributed string
    NSMutableAttributedString *mutableAttr = [[textView attributedText] mutableCopy];
    //Remove the attachment
    [mutableAttr replaceCharactersInRange:range withString:@""]; 
    //Set the new attributed string
    [textView setAttributedText:mutableAttr];