Moving the view so a Textfield can be seen when keyboard is shown

Found this great article that shows how to scroll the view so that a textfield is in view when the keyboard appears.

http://de-co-de.blogspot.com/2009/03/moving-uitextfield-above-keyboard.html

I’ve copied the code below so that I have a reference to it as well.

You also need to ensure the following steps are followed…

  • Make your controller implement UITextViewDelegate
  • setup your textfield’s (s) delegate to be your controller
  • in the controller @interface add an int verticalOffset
  • in the controller @implementation add the functions below
  • #pragma mark "-- text editing support --"
    // Animate the entire view up or down, to prevent the keyboard from covering the text field.
    - (void)moveView:(int)offset {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        // Make changes to the view's frame inside the animation block. They will be animated instead
        // of taking place immediately.
        CGRect rect = self.view.frame;
        rect.origin.y -= offset;
        rect.size.height += offset;
        self.view.frame = rect;
    
        [UIView commitAnimations];
    }
    
    - (BOOL)textFieldShouldReturn:(UITextField *) sender {
        [sender resignFirstResponder];
        if (verticalOffset!=0) {
            [self moveView: -verticalOffset];
            verticalOffset = 0;
        }
        return TRUE;
    }
    
    - (void)textFieldDidBeginEditing:(UITextField *)theTextField {
        int wantedOffset = theTextField.frame.origin.y-200;
        if ( wantedOffset < 0 ) {
            wantedOffset = 0;
        }
        if ( wantedOffset != verticalOffset ) {
            [self moveView: wantedOffset - verticalOffset];
            verticalOffset = wantedOffset;
        }
    }
    


Leave a Reply