I have a simple UIScrollView
with 2 UITextField
s in it, and a piece of code which does not make any sense to me, but it is working.
This is the screen (I am using Auto Layout):
Here is the code:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)keyboardWillShow:(NSNotification*) notif
{
NSDictionary *info = [notif userInfo];
CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
UIEdgeInsets contentInset = self.scrollView.contentInset;
contentInset.bottom = keyboardRect.size.height;
self.scrollView.contentInset = contentInset;
}
- (void) keyboardWillHide:(NSNotification*) notif
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_scrollView.contentInset = contentInsets;
}
What I would expect is to move the scrollview by 352 points up (the height of the keyboard) since that is the value I set contentInset.bottom
to, and it should not matter which UITextField
is selected, since the height of the keyboard is always the same.
However the result is that it scroll up just so the UITextField
that is the first responder will not be covered by the keyboard. So it scrolls more in case of the bottom UITextField
and less in case of the top one. This looks way better of course than the result I expect, but I can't figure out why is it working. Anyone with an explanation?