Created
August 29, 2013 03:12
-
-
Save markSci5/6373877 to your computer and use it in GitHub Desktop.
Adjust view to show fields when keyboard appears
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
#pragma mark - UITextField Delegates | |
-(void)textFieldDidBeginEditing:(UITextField *)textField | |
{ | |
self.activeTextField = textField; | |
} | |
#pragma mark - Keyboard Notification Methods | |
-(void)keyboardWillShow:(NSNotification*) notification | |
{ | |
/* | |
This will check if the currently active field will be hidden | |
by the keyboard when it appears. If it will be, view's frame | |
will be adjusted upwards so that the active field will be visible. | |
*/ | |
NSDictionary *info = [notification userInfo]; | |
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; | |
CGFloat keyboardHeight = kbSize.height; | |
NSLog(@"%f", kbSize.height); | |
CGRect selfViewFrame = self.view.frame; | |
selfViewFrame.size.height -= keyboardHeight; | |
CGPoint activeFieldOrigin = self.activeTextField.frame.origin; | |
activeFieldOrigin.y += self.activeTextField.frame.size.height + 10; | |
if(!CGRectContainsPoint(selfViewFrame, activeFieldOrigin)){ | |
[UIView beginAnimations:nil context:NULL]; | |
[UIView setAnimationDuration:0.3]; | |
CGRect selfViewRect = self.view.frame; | |
selfViewRect.origin.y -= keyboardHeight - (selfViewRect.size.height - activeFieldOrigin.y); | |
self.view.frame = selfViewRect; | |
[UIView commitAnimations]; | |
} | |
} | |
-(void)keyboardWillHide:(NSNotification*)notification | |
{ | |
//Returns the main view's frame back into it's original position. | |
[UIView beginAnimations:nil context:NULL]; | |
[UIView setAnimationDuration:0.3]; | |
CGRect selfViewRect = self.view.frame; | |
selfViewRect.origin.x = 0; | |
selfViewRect.origin.y = 0; | |
self.view.frame = selfViewRect; | |
[UIView commitAnimations]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment