Skip to content

Instantly share code, notes, and snippets.

@markSci5
Created August 29, 2013 03:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markSci5/6373877 to your computer and use it in GitHub Desktop.
Save markSci5/6373877 to your computer and use it in GitHub Desktop.
Adjust view to show fields when keyboard appears
#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