- (void)setNotification { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil]; } - (void)closeNotification { [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil]; } - (void)keyboardWillChangeFrame:(NSNotification *)notification { NSDictionary *dict = [notification userInfo]; // 鍵盤彈出和收回的時間 CGFloat duration = [[dict objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]; // 鍵盤初始時刻的frame CGRect beginKeyboardRect = [[dict objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]; // 鍵盤停止後的frame CGRect endKeyboardRect = [[dict objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 相減為鍵盤高度 CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y; // 創建appDelegate單例對象 AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; // 初始化一個數組,UIWindow的所有子視圖 NSArray *array = appDelegate.window.subviews; // 獲取當前Controller的view視圖 UIView *view = appDelegate.window.subviews[array.count - 1]; // textField相對於UIWindow的frame CGRect selfFrameFromUIWindow = [self convertRect:self.bounds toView:appDelegate.window]; // textField底部距離屏幕底部的距離 CGFloat bottomHeight = [UIScreen mainScreen].bounds.size.height - selfFrameFromUIWindow.origin.y - selfFrameFromUIWindow.size.height; // 初始化一個frame,大小為UIWindow的frame CGRect windowFrame = appDelegate.window.frame; // 把這個frame的y值增加或減少相應的高度(這裡的40是textField底部和鍵盤頂部的距離) windowFrame.origin.y += yOffset + bottomHeight - 40; // 根據yOffset判斷鍵盤是彈出還是收回 if (yOffset < 0) { // 鍵盤彈出,改變當前Controller的view的frame [UIView animateWithDuration:duration animations:^{ view.frame = windowFrame; }]; } else { // 鍵盤收回,把view的frame恢復原狀 [UIView animateWithDuration:duration animations:^{ view.frame = appDelegate.window.frame; }]; } }