简体   繁体   中英

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 (ie, @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?

在此处输入图片说明

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 

Set the delegate of UITextView . Implement the delegate method as follows:-

- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text{

    if([text isEqualToString:@""]){//means user pressed backspace
        NSArray *arrayOfWords = [textView.text componentsSeparatedByString:@" "];// Separate all the words separated by space
        NSString *lastWord = [arrayOfWords lastObject];// Get the last word (as we are working with backspace)

        if([lastWord hasPrefix:@"@"]){
            textView.text = [textView.text stringByReplacingOccurrencesOfString:lastWord withString:@" "];//if last word starts with @, then replace it with space
        }
    }

    return YES;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM