開啟鍵盤遮住View的問題解決方法

chenyxh2005發表於2014-12-10

是什麼大問題,我們使用點小小的手段就可以解決。

首先我們要知道鍵盤的高度是固定不變的,不過在IOS 5.0 以後鍵盤的高度貌似不是216了,不過不要緊,我們調整調整就是了:

  iPhone ipad
豎屏(portrait) 216 264
橫屏(landScape) 140 352

我們採取的方法就是在textField(有可能是其他控制元件)接收到彈出鍵盤事件時把self.view整體上移216px了(我們就以iPhone豎屏為例了)。

有關View的frame,origin,size之類的知識點不懂的請參看我的另一篇博文: <<有關View的幾個基礎知識點>>

首先我們要設定textField的代理,我們就設為當前控制器了。

textField,delegate=self;

然後我們在當前控制器實現下面三個委託方法:

  1. - (void)textFieldDidBeginEditing:(UITextField *)textField  
  2. //當點觸textField內部,開始編輯都會呼叫這個方法。textField將成為first responder   
  3.        NSTimeInterval animationDuration = 0.30f;      
  4.       CGRect frame = self.view.frame;  
  5.       frame.origin.y -=216;  
  6.       frame.size.height +=216;  
  7.       self.view.frame = frame;  
  8.        [UIView beginAnimations:@"ResizeView" context:nil];  
  9.        [UIView setAnimationDuration:animationDuration];  
  10.        self.view.frame = frame;                  
  11.        [UIView commitAnimations];                  
  12. }  


  1. - (BOOL)textFieldShouldReturn:(UITextField *)textField   
  2. {//當使用者按下ruturn,把焦點從textField移開那麼鍵盤就會消失了  
  3.         NSTimeInterval animationDuration = 0.30f;  
  4.         CGRect frame = self.view.frame;      
  5.         frame.origin.y +=216;        
  6.         frame.size. height -=216;     
  7.         self.view.frame = frame;  
  8.     //self.view移回原位置    
  9.     [UIView beginAnimations:@"ResizeView" context:nil];  
  10.     [UIView setAnimationDuration:animationDuration];  
  11.         self.view.frame = frame;                  
  12.         [UIView commitAnimations];  
  13.         [textField resignFirstResponder];     
  14. }         

相關文章