3

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;
}
Pwner
  • 3,714
  • 6
  • 41
  • 67
  • Did you see this? http://stackoverflow.com/questions/388237/getting-the-value-of-a-uitextfield-as-keystrokes-are-entered?rq=1 – warpedspeed Aug 30 '13 at 00:41

1 Answers1

3

I wouldn't even deal with the delegate. Just use UITextFieldTextDidChangeNotification to be informed of the change after the fact. Then you don't have to worry about appending the changes to the string, you can just access the text as a whole.

[[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
    NSString *string = someTextFieldReference.text;
}];

Or as pointed out in the answers in the post @warpedspeed linked, you could just add a target for the text field's editing changed control event, like so:

[myTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];


- (void)textFieldDidChange:(UITextField *)sender
{
    NSLog(@"%@",sender.text);
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281