1

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];
    }
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152

2 Answers2

1

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;

Joseph Lin
  • 3,324
  • 1
  • 29
  • 39
  • @Joe This lets me enter the textFieldDidBeginEditing but then the code crashes with a 'NSInvalidArgumentException', reason: '-[UIView scrollToView:]: unrecognized selector sent to instance 0x4e47840' – Nick LaMarca Apr 22 '11 at 18:44
  • There's no `scrollToView` in the code sample you post. Can you do a search and see where you called that method in your code? – Joseph Lin Apr 22 '11 at 18:50
  • @Joe got it, forgot to add the UITextFiledDelegate to the .h file – Nick LaMarca Apr 22 '11 at 22:08
0

I would highly recommend using a UITableViewController and put your UITextField into the table. That way the keyboard-hiding issue is solved for you by the system.

Till
  • 27,559
  • 13
  • 88
  • 122