Johno2110 Johno2110 - 4 months ago 16
iOS Question

Scroll view not scrolling back down when keyboard closes

I have used apples guide on Moving content located under the keyboard

Guide here

It works very well in scrolling up when the keyboard opens but when the keyboard is closed it doesn't scroll back down and I am left with the top of the scroll view cut off.

my Code

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
_myScrollView.contentInset = contentInsets;
_myScrollView.scrollIndicatorInsets = contentInsets;

// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[self.myScrollView scrollRectToVisible:activeField.frame animated:YES];
}
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_myScrollView.contentInset = contentInsets;
_myScrollView.scrollIndicatorInsets = contentInsets;
}

Answer

This is the code I use when the keyboard resigns. I had trouble with your original code because it seems not to want to work in iOS 7.

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    CGRect frame = self.scrollView.frame;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    //add keyboard size to current scrollview frame
    frame.size.height += keyboardBounds.size.height;

    //apply frame to scrollview
    self.scrollView.frame = frame;

    [UIView commitAnimations];
}
Comments