当用户输入 UITextField 时,我需要实时了解文本字段中的整个字符串。我这样做的方法是监听UITextFieldDelegate回调。这个回调的问题是它在实际插入附加文本之前被触发。由于这个和其他各种极端情况,我需要编写这个极其复杂的代码。有没有更简单(更少代码)的方式来做同样的事情?
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString* entireString = nil;
if (string.length == 0) {
// When hitting backspace, 'string' will be the empty string.
entireString = [textField.text substringWithRange:NSMakeRange(0, textField.text.length - 1)];
} else if (string.length > 1) {
// Autocompleting a single word and then hitting enter. For example,
// type in "test" and it will suggest "Test". Hit enter and 'string'
// will be "Test".
entireString = string;
} else {
// Regular typing of an additional character
entireString = [textField.text stringByAppendingString:string];
}
NSLog(@"Entire String = '%@'", entireString);
return YES;
}