iOS从UITextView中删除单词

假设,我在UITextView中有一个字符串:

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

当我点击文本时,我可以逐个删除字符。 但我想要的是,如果任何单词以@开头(如:@are),那么当我点击该单词并按退格键时,应删除整个单词(即@are)而不是字符。 是否有可能当我点击任何带有前缀’@’的单词(如:@are)时,它会突出显示并按退格键会删除该单词?

我怎样才能做到这一点?

在此处输入图像描述

好的我有解决方案和工作:)

 - (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 

设置UITextViewdelegate 。 实现委托方法如下: –

 - (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; }