As the user is typing into a UITextField, I need to know in realtime the entire string in the text field. My way of doing this was to listen for a UITextFieldDelegate callback. The problem with this callback is that it is triggered right before the additional text is actually inserted. Because of this and various other corner cases, I needed to write this horrendously complex code. Is there a simpler (less code) way of doing the same thing?
- (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;
}