Reputation: 1131
I have used apples guide on Moving content located under the keyboard
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;
}
Upvotes: 2
Views: 1431
Reputation: 6335
A working Swift 2.0 code translation for urnotsam's Objective C code:
func keyboardWillBeHidden(notification: NSNotification) {
// Once keyboard disappears, restore original positions
let info: NSDictionary = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var scrollViewFrame: CGRect = self.scrollView.frame
// Begin animation
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.3)
scrollViewFrame.size.height += (keyboardSize?.height)!
// Apply it
self.scrollView.frame = scrollViewFrame
// Now animate
UIView.commitAnimations()
}
Upvotes: 0
Reputation: 770
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];
}
Upvotes: 2