How to scroll the screen using the iPhone keyboard

advertisements

I'm working on an app that is in landscape view. I'm using a few UITextFields that when double tapped it will give you the ability to edit the TextFields. My question is how do I get the screen to scroll so the user can edit entire screen while the keypad is shown?


Using contentInset and scrollRectToVisible has served me well. The code below insets the scroll view so it is not covered by the keyboard, and then scrolls the content to display the the text field.

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    CGRect kbFrame;
    [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&kbFrame];
    float kbHeight = [self convertRect:kbFrame fromView:nil].size.height;
    float d = kbHeight - self.frame.origin.y / self.transform.a;
    d = d < 0 ? 0 : d;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, d, 0.0);

    self.contentInset = contentInsets;
    self.scrollIndicatorInsets = contentInsets;

    UIView *responder = /* ... your text field ... */
    [self scrollRectToVisible:responder.frame animated:YES];
    [self performSelector:@selector(flashScrollIndicators) withObject:nil afterDelay:0.0];
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;

    [[aNotification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];

    [UIView animateWithDuration:animationDuration
                          delay:0
                        options:animationCurve
                     animations:^{
                         self.contentInset = UIEdgeInsetsZero;
                         self.scrollIndicatorInsets = UIEdgeInsetsZero;
                     }
                     completion:nil];

    [self setContentOffset:CGPointMake(0, 0) animated:YES];
    self.scrollEnabled = NO;
}