Search code examples
iosanimationuitextfielduitextfielddelegate

UITextField clear button use with screen animation


I have a screen that performs an animation (shifts screen up) when the user enters a text field so it stays visible when entering data then shifts back down once the user is done entering data. The problem I am having is when the user tries to use the clear button inside the text box (set with site_TextField.clearButtonMode = UITextFieldViewModeAlways). The flow for the text fields when the clear button is pressed should be:

textFieldShouldEndEditing --> textFieldDidEndEditing --> textFieldShouldClear --> textFieldShouldBeginEditing --> textFieldDidBeginEditing

However, the textFieldDidEndEditing method is where the animation is called from and when the animation is performed the above sequence stops and textFieldShouldClear is not called. I am hoping it is something simple I am just missing. Any input is appreciated!

- (BOOL)textFieldShouldBeginEditing:(UITextField *) textField
{
    NSLog(@"In textFieldShouldBeginEditing");
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == site_TextField || textField == phone_TextField) {
        [self animateTextField: textField up: YES];
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"In textFieldShouldEndEditing");
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == site_TextField || textField == phone_TextField) {
        [self animateTextField: textField up: NO];
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {

    NSLog(@"In textFieldShouldClear");
    return YES;
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    if (textField != site_TextField && textField != phone_TextField) {
        return;
    }

    int movementDistance = 0;
    if (textField == site_TextField) {
        movementDistance = 100;
    } else if (textField == phone_TextField) {
        movementDistance = 170;
    }

    int movement = (up ? -movementDistance : movementDistance);

    [UIView animateWithDuration:0.3
                          delay:0.0
                        options: UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
                    }
                     completion:^(BOOL finished){
                     }];
}

Solution

  • I suspect the first textFieldShouldEndEditing and textFieldDidEndEditing are triggered by touch down on the clear button. And the textFieldShouldClear is triggered by touch up. But with your animation, the textField moves immediately after the touch down, so the touch up does not register. Try using the textField didEndOnExit event to trigger a method which does the animation down.