Created
August 14, 2012 00:44
-
-
Save dumbfingers/3345198 to your computer and use it in GitHub Desktop.
This file contains hidden or 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)viewWillAppear:(BOOL)animated { | |
[self registerForKeyboardNotifications]; | |
} | |
- (void)viewWillDisappear:(BOOL)animated { | |
[self unregisterForKeyboardNotifications]; | |
} | |
- (void)hideKeyboard { | |
[scrollView resignFirstResponder]; | |
} | |
// Call this method somewhere in the view controller setup code. | |
- (void)registerForKeyboardNotifications | |
{ | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; | |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; | |
} | |
// Call this to unregister the notifications | |
- (void)unregisterForKeyboardNotifications { | |
[[NSNotificationCenter defaultCenter] removeObserver:self]; | |
} | |
// Called when the UIKeyboardDidShowNotification 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); | |
scrollView.contentInset = contentInsets; | |
scrollView.scrollIndicatorInsets = contentInsets; | |
// If active text field is hidden by keyboard, scroll it so it's visible | |
// Your application might not need or want this behavior. | |
CGRect aRect = self.view.frame; | |
aRect.size.height -= kbSize.height; | |
CGPoint origin = activeField.frame.origin; | |
origin.y -= scrollView.contentOffset.y; | |
if (!CGRectContainsPoint(aRect, origin) ) { | |
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-(aRect.size.height)); | |
[scrollView setContentOffset:scrollPoint animated:YES]; | |
} | |
} | |
// Called when the UIKeyboardWillHideNotification is sent | |
- (void)keyboardWillBeHidden:(NSNotification*)aNotification | |
{ | |
UIEdgeInsets contentInsets = UIEdgeInsetsZero; | |
scrollView.contentInset = contentInsets; | |
scrollView.scrollIndicatorInsets = contentInsets; | |
} | |
- (void)textFieldDidBeginEditing:(UITextField *)textField | |
{ | |
activeField = textField; | |
} | |
- (void)textFieldDidEndEditing:(UITextField *)textField | |
{ | |
activeField = nil; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment