I have a UIScrollView with a UIView inside based on an article how to use autolayout with input fields. The article explains how to set the UIView to equal height and with of the normal view, for more information: https://www.natashatherobot.com/ios-autolayout-scrollview/.
Now I have multiple UITextFields inside my content view. When I press a UITextField, I want my view to show the keyboard and scroll to the UITextField. At first, I tried an approach used by multiple, but the problem is, at the bottom of the screen, I get a lot of blank space from the bottom of the view which is unwanted. The approach I tried is using the following lines:
- (void)keyboardWillHide:(NSNotification *)notification {
[[self scrollView] setContentInset:UIEdgeInsetsMake([[self scrollView] contentInset].top, 0.0f, 0.0f, 0.0f)];
}
- (void)keyboardWillShow:(NSNotification *)notification {
[[self scrollView] setContentInset:UIEdgeInsetsMake([[self scrollView] contentInset].top, 0.0f, [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height, 0.0f)];
}
To change this, I thought changing the bottom to a more appropriate value would do the trick, but when I do this, the view won't scroll to the UITextField anymore when I press it. I can manually scroll the the field though. The way I achieved this, is using the following:
- (void)keyboardWillShow:(NSNotification *)notification {
float keyboard = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
float offset = [[[[self contentView] subviews] lastObject] frame].size.height + [[[[self contentView] subviews] lastObject] frame].origin.y + 30.0f;
if ([[self contentView] frame].size.height - [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height < offset) {
[[self scrollView] setContentInset:UIEdgeInsetsMake([[self scrollView] contentInset].top, 0.0f, offset - ([[self view] frame].size.height - keyboard), 0.0f)];
}
}
Does anyone know how I can ignore the blank space under the UITextFields when scrolling, but allow the scrollview to scroll to the selected UITextField. I tried using the method scrollRectToVisible, but this doesn't do anything.