Dowemo
0 0 0 0


Question:

I am working on an app that lets the user mention other users by typing @username. Though I have found a way to detect the @ character and highlight the selected username within the text string, I am not sure how to manage the event when the user mentions a user but then wants to delete that user from the mention.

For example, in the Facebook app, when you mention someone, that person's name in the UITextView is highlighted with a light-blue background. However, when you start deleting that mention, the whole mention gets deleted when you delete the last character in the attributed string.

I am, therefore, looking for a way that I can capture when the user deletes the last character of an attributed string in order to delete that whole attributed string and completely remove the mention from the text view.


Best Answer:


In order to achieve the desired behaviour mentioned above, I ended up doing the following. I implemented all these methods as part of the view controller where my UITextView is placed, so I added the UITextViewDelegate protocol to my view controller. Then, I implemented the following methods:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //if this is true, then the user just deleted a character by using backspace
    if(range.length == 1 && text.length == 0){            
        NSUInteger cursorPosition = range.location; //gets cursor current position in the text
        NSRange attrRange; //will store the range of the text that holds specific attributes
        NSDictionary *attrs = [_content.attributedText attributesAtIndex:cursorPosition effectiveRange:&attrRange];
        //check if the attributes of the attributed text in the cursor's current position correspond to what you want to delete as a block
        if([attrs objectForKey:NSBackgroundColorAttributeName]){
            NSAttributedString *newStr = [_content.attributedText attributedSubstringFromRange:NSMakeRange(0, attrRange.location)]; //creates a new NSAttributed string without the block of text you wanted to delete
            _content.attributedText = newStr; //substitute the attributed text of your UITextView
            return NO;
        }
    }
    return YES;
}



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs