1.首先註冊系統通知
動畫
//監聽鍵盤通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
2.鍵盤將要改變時的相應處理 spa
-(void)keyboardWillChangeFrameNotification:(NSNotification *)note{ //取出鍵盤動畫的時間(根據userInfo的key----UIKeyboardAnimationDurationUserInfoKey) CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; //取得鍵盤最後的frame(根據userInfo的key----UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";) CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; //計算控制器的view須要平移的距離 CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height; //執行動畫 [UIView animateWithDuration:duration animations:^{ //平移 self.view.transform = CGAffineTransformMakeTranslation(0, transformY); }]; }
3.這樣其實還沒完(存在內存隱患)還須要重寫dealloc方法3d
-(void)dealloc{code
//使用通知中心後必須重寫dealloc方法,進行釋放(ARC)(非ARC還須要寫上[super dealloc];)orm
//removeObserver和 addObserver相對應.
server
[[NSNotificationCenter defaultCenter] removeObserver:self];內存
}rem