Search code examples
iostextfieldtouch-event

ios/xcode/objective c: Capture last keystroke in textfield


I have a method to enable the save button that I want to fire when the user meets several conditions, for example, username is at least 4 characters. To test these conditions I need to check with every keystroke. What is best touch event (through storyboard) to capture this?

Have tried "Editing did end" however, that doesn't fire until you click out of textfield. I'd rather see button enabled as soon as textfield has acceptable entry. Also tried on touchup inside and value changed but neither seem to work.

What is best touch event so that as soon as user types fourth character, button is enabled?

Here is action method that textfield is wired to. Note it does not say anything about touch event which is present in storyboard.

- (IBAction)changedText:(id)sender {
    [self updateSaveButton];

-(void) updateSaveButton
{
    NSString *name = self.username.text;
    NSLog(@"update save button called");
    self.submitButton.enabled = (name.length > 3);
}

Solution

  • What I do is to assign the text field a delegate. In this case, the delegate would whatever is the instance whose class's code you have shown in your question.

    The delegate is sent a bunch of delegate messages, documented in UITextFieldDelegate. In this case, the one I would use is textField:shouldChangeCharactersInRange:replacementString:, which fires every time the user does anything that proposed to change the text in the field.

    Simply respond as you see fit, and return YES to allow the change to take place.

    Alternatively, you can treat the text field as a control (UIControl) and use the text field's Editing Changed control event to set up a target-action pair. But in actual practice I always end up using the delegate method instead.