轉自http://blog.csdn.net/u011374699/article/details/45894303
原本用的方法是int offset = textfield.frame.origin.y + height - self.view.frame.size.height + 216(鍵盤高度)來計算y軸移動的偏移量。如果offset大於0,就向上偏移。
這裏有個問題:如果textfield所在view外面嵌套了好多層佈局,而且使用autoLayout,那麼,textfield.frame.origin.y=0,導致offset小於0而沒有向上偏移。
- // 開始編輯輸入框時,鍵盤出現,視圖的Y座標向上移動offset個單位,騰出空間顯示鍵盤
- - (void)textFieldDidBeginEditing:(UITextField *)textField
- {
- CGRect textFrame = textField.frame;
- CGPoint textPoint = [textField convertPoint:CGPointMake(0, textField.frame.size.height) toView:self.view];// 關鍵的一句,一定要轉換
- int offset = textPoint.y + textFrame.size.height + 216 - self.view.frame.size.height + 24;// 24是textfield和鍵盤上方的間距,可以自由設定
- NSTimeInterval animationDuration = 0.30f;
- [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
- [UIView setAnimationDuration:animationDuration];
- // 將視圖的Y座標向上移動offset個單位,以使下面騰出地方用於軟鍵盤的顯示
- if (offset > 0) {
- self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
- }
- [UIView commitAnimations];
- }
- // 用戶輸入時
- - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
- // 輸入結束後,將視圖恢復到原始狀態
- self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
- return YES;
- }