在viewController里:
// 注册键盘事件监听器,键盘消失和键盘显示
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
- (void)keyboardWasShown:(NSNotification*)aNotification {
// 键盘显示的同时,将界面上移一段距离
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect aRect = self.view.frame;
aRect.size.height -= 40;//可以自定义
self.view.frame = aRect;
[UIView commitAnimations];
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
//键盘隐藏时,将界面恢复过来
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect aRect = self.view.frame;
aRect.size.height += 40;
self.view.frame = aRect;
[UIView commitAnimations];
}