Last active
November 14, 2018 18:46
-
-
Save braking/5575962 to your computer and use it in GitHub Desktop.
Adjust content insets of a tableview when keyboard opens.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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)dealloc | |
{ | |
[[NSNotificationCenter defaultCenter] removeObserver:self]; | |
} | |
- (void)keyboardWillShow:(NSNotification *)notification | |
{ | |
CGSize keyboardSize = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; | |
NSNumber *rate = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]; | |
UIEdgeInsets contentInsets; | |
if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) { | |
contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0); | |
} else { | |
contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.width), 0.0); | |
} | |
[UIView animateWithDuration:rate.floatValue animations:^{ | |
self.tableView.contentInset = contentInsets; | |
self.tableView.scrollIndicatorInsets = contentInsets; | |
}]; | |
[self.tableView scrollToRowAtIndexPath:self.editingIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; | |
} | |
- (void)keyboardWillHide:(NSNotification *)notification | |
{ | |
NSNumber *rate = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]; | |
[UIView animateWithDuration:rate.floatValue animations:^{ | |
self.tableView.contentInset = UIEdgeInsetsZero; | |
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero; | |
}]; | |
} |
concerning editIndexPath:
i added
@interface MyTableViewController ()
{
NSIndexPath* editingIndexPath;
}
@end
to the top of my viewcontroller.
Then i set the indexPath when i call my textedit method.
Should be UIKeyboardFrameEndUserInfoKey. In iOS11, the height is 0 when you use UIKeyboardFrameBeginUserInfoKey! Also, on iPhoneX the height is 75 pts more in portrait mode. So, you are better off adjusting a constraint of the tableview that is pinned to the bottom of the superview because the keyboard is pinned to the bottom of the superview too. Then you don't need to change the tableview contentInset at all. This works on all devices.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hmm, i had to change keyboardWillShow to the following:
else the inset was to large in landscape mode.