- (void)viewDidLoad { [super viewDidLoad]; //增加監聽,當鍵盤出現或改變時收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardWillShowNotification
object:nil];
//增加監聽,當鍵退出時收出消息[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardWillHideNotification
object:nil];
}//當鍵盤出現或改變時調用
- (void)keyboardDidShow:(NSNotification *)notification{
NSDictionary *userInfo = [notification userInfo];
CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
_keyBoardHeight = keyboardSize.height;
[self changeViewYByShow];
}
//當鍵盤隱藏時調用
- (void)keyboardDidHide:(NSNotification *)notification{
_keyBoardHeight = 0;
[self changeViewYByHide];
}
#pragma mark - private methods
- (void)changeViewYByShow{
[UIView animateWithDuration:0.2 animations:^{
CGRect rect = self.view.frame;
rect.origin.y -= self.keyBoardHeight;
self.view.frame = rect;
}];
}
- (void)changeViewYByHide{
CGRect rect = self.view.frame;
rect.origin.y = 64;
self.view.frame = rect;
}