Search code examples
iphoneios4

Setting Up Textfield Animationd To Move TextFields Above Keyboard


I know there is alot on this topic already. I got the code below from another question, but I have no idea how to set it up to use. Can someone give me a detailed step by step on how to actually setup the process of moving a textfield above the keyboard when the keyboard comes up then moving it back when the editing is done.

 - (void)textFieldDidBeginEditing:(UITextField *)textField
    {
        [self animateTextField: textField up: YES];
    }


    - (void)textFieldDidEndEditing:(UITextField *)textField
    {
        [self animateTextField: textField up: NO];
    }

    - (void) animateTextField: (UITextField*) textField up: (BOOL) up
    {
        const int movementDistance = 80; // tweak as needed
        const float movementDuration = 0.3f; // tweak as needed

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

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
        [UIView commitAnimations];
    }

Solution

  • Is the textFieldDidBeginEditing: or textFieldDidEndEditing: ever get called?

    If not, you might not setting your text field's delegate correctly.

    When you declare you text field (or, if you're using IB, in viewDidLoad), add this: yourTextField.delegate = self;