//在view將要出現的時候重載viewWillAppear方法添加通知 監聽事件 keyboardWillShow: keyboardWillHide:html
- (void)viewWillAppear:(BOOL)animatedios
{app
[super viewWillAppear:animated];ide
[[NSNotificationCenter defaultCenter] addObserver:self動畫
selector:@selector(keyboardWillShow:)spa
name:UIKeyboardWillShowNotificationorm
object:nil];server
[[NSNotificationCenter defaultCenter] addObserver:selfhtm
selector:@selector(keyboardWillHide:)對象
name:UIKeyboardWillHideNotification
object:nil];
}
//當你頁面跳轉後,要移除兩個通知 由於通知不移除,會一直存在在內存中
- (void) viewDidDisappear:(BOOL)paramAnimated {
[super viewDidDisappear:paramAnimated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//實現監聽事件的兩個方法
- (void)keyboardWillShow:(NSNotification *)note {
//獲取鍵盤的高度
//通知消息 NSNotification中的 userInfo字典中包含鍵盤的位置和大小信息,對應的key爲
//UIKeyboardFrameBeginUserInfoKey
//UIKeyboardFrameEndUserInfoKey
//對應的Value是個NSValue對象,內部包含CGRect結構,分別爲鍵盤起始時和終止時的位置信息。
//UIKeyboardAnimationDurationUserInfoKey
對應的Value也是NSNumber對象,內部爲double類型的數據,表示鍵盤h顯示或消失時動畫的持續時間。
//UIKeyboardAnimationCurveUserInfoKey
//對應的Value是NSNumber對象,內部爲UIViewAnimationCurve類型的數據,表示鍵盤顯示或消失的動畫類型。
// UIKeyboardFrameEndUserInfoKey 動畫前鍵盤的位置,包含CGRect的NSValue
//UIKeyboardFrameEndUserInfoKey 動畫結束後的鍵盤位置,包含CGRect的NSValue
//NSDictionary* info = [aNotification userInfo];
//CGRect _rect =[[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//note.info[objectForKey:UIKeyboardFrameEndUserInfoKey]
CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat deltaY=keyBoardRect.size.height;
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
self.view.transform=CGAffineTransformMakeTranslation(0, -deltaY);
}];
}
- (void)keyboardWillHide:(NSNotification *)note {
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
// CGAffineTransformIdentity 記錄先前的位置
// CGAffineTransformMakeTranslation : 每次都是以最初位置的中心點爲參考
// CGAffineTransformTranslate 每次都是以傳入的transform爲參照(既 有疊加效果)
// CGAffineTransformIdentity 最初位置的中心點
self.view.transform = CGAffineTransformIdentity;
}];
}