Skip to content

Instantly share code, notes, and snippets.

@mjjimenez
Created October 18, 2013 06:28
Show Gist options
  • Save mjjimenez/7037283 to your computer and use it in GitHub Desktop.
Save mjjimenez/7037283 to your computer and use it in GitHub Desktop.
Adjust offset of view when keyboard hides a textfield
- (void)viewWillAppear:(BOOL)animated
{
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
// unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
#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