Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS remove word from UITextView

Suppose, I have a string in a UITextView that is :

NSString *str = @"Hello world. What @are you @doing ?" 

When I tap on the text, I can delete the character by character. But what I want is if any word starts with @ (like: @are) then when I tap on that word and press backspace the entire word (i.e, @are)should be deleted instead of a character. Is it possible that when I tap on any word that has a prefix '@' (like: @are) it will be highlighted and press backspace will delete that word ?

How can I do that?

like image 692
Samuel Patterson Avatar asked Sep 02 '16 10:09

Samuel Patterson


1 Answers

enter image description here

Ok i have solution for that and Working :)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if ([string isEqualToString:@""]) {

    UITextRange* selectedRange = [textField selectedTextRange];
    NSInteger cursorOffset = [textField offsetFromPosition:0 toPosition:selectedRange.start];
    NSString* text = textField.text;
    NSString* substring = [text substringToIndex:cursorOffset];
    NSString* lastWord = [[substring componentsSeparatedByString:@" "] lastObject];

    if ([lastWord hasPrefix:@"@"]) {
        // Delete word

        textField.text =  [[self.textField text] stringByReplacingOccurrencesOfString:lastWord withString:@""];
        return NO;
    }
}
return YES;
}// return 
like image 50
Prashant Tukadiya Avatar answered Nov 15 '22 20:11

Prashant Tukadiya