虛擬鍵盤彈出擋住textfield的分析以及解決辦法

轉自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而沒有向上偏移。

以下是經本人測試且有效的辦法:

  1. // 開始編輯輸入框時,鍵盤出現,視圖的Y座標向上移動offset個單位,騰出空間顯示鍵盤  
  2. - (void)textFieldDidBeginEditing:(UITextField *)textField  
  3. {  
  4.       
  5.     CGRect textFrame = textField.frame;  
  6.     CGPoint textPoint = [textField convertPoint:CGPointMake(0, textField.frame.size.height) toView:self.view];// 關鍵的一句,一定要轉換  
  7.     int offset = textPoint.y + textFrame.size.height + 216 - self.view.frame.size.height + 24;// 24是textfield和鍵盤上方的間距,可以自由設定  
  8.   
  9.     NSTimeInterval animationDuration = 0.30f;  
  10.     [UIView beginAnimations:@"ResizeForKeyboard" context:nil];  
  11.     [UIView setAnimationDuration:animationDuration];  
  12.       
  13.     // 將視圖的Y座標向上移動offset個單位,以使下面騰出地方用於軟鍵盤的顯示  
  14.     if (offset > 0) {  
  15.         self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.widthself.view.frame.size.height);  
  16.     }  
  17.       
  18.     [UIView commitAnimations];  
  19. }  
  20.   
  21. // 用戶輸入時  
  22. - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{  
  23.     // 輸入結束後,將視圖恢復到原始狀態  
  24.     self.view.frame = CGRectMake(00self.view.frame.size.widthself.view.frame.size.height);  
  25.     return YES;  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章