I got a UIViewController and I have a UIScrollView with a few UITextFields inside. I got a piece of code from apple that seems to move the content from underneath the keyboard.
- (void)keyboardWasShown:(NSNotification *)notification
{
// Step 1: Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Step 3: Scroll the target text field into view.
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardSize.height;
if (!CGRectContainsPoint(aRect, self.firstResponder.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, self.firstResponder.frame.origin.y - (keyboardSize.height-10));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
My UIScrollView is 320×416 because I have a navigation bar. Also my keyboard gets 44 more pixels because I’m adding a UIToolBar to it, so the code is not really working. I tried all kinds of configurations to solve two problems:
- The last two fields are being covered by the UIToolBar + keyboard but only the last one triggers the UIScrollView movement.
- Besides the UIScrollView is moving, the UITextField is still behind the keyboard due to the UIToolBar.
UPDATE: This works, but I’m pretty sure is wrong, and if is right, I don’t know why, doesn’t makes sense to me. Can someone fix / explain it?
- (void)keyboardWasShown:(NSNotification *)notification
{
// Step 1: Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 44.0f, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Step 3: Scroll the target text field into view.
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardSize.height + 44.0f;
if (!CGRectContainsPoint(aRect, self.firstResponder.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, self.firstResponder.frame.origin.y - (keyboardSize.height-10.0f - 44.0f - 44.0f - 44.0f));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
UPDATE1: There is another bug, I have a previous button in the UIToolBar, if I tap the last text field, the scroll view goes up, If I move back to the first text view, it is outside the view, because the scroll view doesn’t rolls down.
After trying a lot to fix apple solution to the problem I ended up writing some code myself after picturing the general idea behind apple code. I think apple code over complicate the problem and doesn’t really work, by the way.