I'd like to move up my view, when the keyboard is shown. The keyboard (height: 216) should push up my view with it's height. Is this possible with a simple code?
To move the view up
, just change its center
. First, keep the original one in a CGPoint
property.
- (void)viewDidLoad
{
...
self.originalCenter = self.view.center;
...
}
Then, change as needed when keyboard shows up:
self.view.center = CGPointMake(self.originalCenter.x, /* new calculated y */);
Finally, restore it when keyboard is hidden:
self.view.center = self.originalCenter;
Add animation sugar as you wish
You have more than one way to know when the keyboard appears.
Observing UIKeyboardDidShowNotification notification.
/* register notification in any of your initWithNibName:bundle:, viewDidLoad, awakeFromNib, etc. */
{
...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
...
}
- (void)keyboardDidShow:(NSNotification *)note
{
/* move your views here */
}
Do the opposite with UIKeyboardDidHideNotification
.
-OR-
Implement UITextFieldDelegate
Detect when editing begin/end to move views around.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
/* keyboard is visible, move views */
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
/* resign first responder, hide keyboard, move views */
}
Depending on the actual text fields you may need to track in which field is the user editing, add a timer to avoid moving views too much.