Last active
July 11, 2019 11:57
-
-
Save kocoai/1984e8870c62e531ba63 to your computer and use it in GitHub Desktop.
keyboard avoid #ios
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)registerForKeyboardNotifications | |
{ | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(keyboardWasShown:) | |
name:UIKeyboardWillShowNotification | |
object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(keyboardWillBeHidden:) | |
name:UIKeyboardWillHideNotification | |
object:nil]; | |
} | |
// Called when the UIKeyboardWillShowNotification 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); | |
self.tableView.contentInset = contentInsets; | |
self.tableView.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, self.activeField.frame.origin) ) | |
{ | |
[self.tableView scrollRectToVisible:self.activeField.frame | |
animated:YES]; | |
} | |
} | |
// Called when the UIKeyboardWillHideNotification is sent | |
- (void)keyboardWillBeHidden:(NSNotification*)aNotification | |
{ | |
self.tableView.contentInset = UIEdgeInsetsZero; | |
self.tableView.contentOffset = CGPointZero; | |
self.tableView.scrollIndicatorInsets = self.contentInset; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment