标签:
在输入框中,需要整体删除诸如 “xxx@xx.com” 或 “@xxxx” 等文本
在删除动作时,获取到当前光标的位置,如果在光标正在处在上述文本范围内,就删除一整串文本
整个过程的关键,就是对 textField:shouldChangeCharactersInRange:replacementString 的实现。代码如下
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (string.length != 0) { return YES; } if (self.quoteText.length == 0) { // quoteText 就是目标字符串 return YES; } // 计算当前光标相对于文本开始位置的偏移量 NSInteger cursorOffset = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start]; NSRange foundRange = [textField.text rangeOfString:self.quoteText]; if (foundRange.location != NSNotFound) { if (foundRange.location <= cursorOffset && foundRange.length + foundRange.location >= cursorOffset) { textField.text = [textField.text stringByReplacingCharactersInRange:foundRange withString:@""]; // 光标移动到删除时的位置 UITextPosition *beginPosition = [textField positionFromPosition:textField.beginningOfDocument offset:foundRange.location]; UITextRange *newRange = [textField textRangeFromPosition:beginPosition toPosition:beginPosition]; [textField setSelectedTextRange:newRange]; return NO; } return YES; } else { return YES; } }
标签:
原文地址:http://www.cnblogs.com/boch2436/p/5842724.html