歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 打開鍵盤遮住View的問題解決方法-iOS開發

打開鍵盤遮住View的問題解決方法-iOS開發

日期:2017/3/1 10:28:40   编辑:Linux編程

默認情況下打開鍵盤會遮住下面的view,帶來一點點困擾,不過這不是什麼大問題,我們使用點小小的手段就可以解決。

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

iphoneipad

豎屏(portrait): 216 264

橫屏(landScape): 140 352

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

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

textField,delegate=self;

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

  1. - (void)textFieldDidBeginEditing:(UITextField *)textField
  2. { //當點觸textField內部,開始編輯都會調用這個方法。textField將成為first responder
  3. NSTimeInterval animationDuration = 0.30f;
  4. <span style="white-space:pre"> </span>float width = self.view.frame.size.width;
  5. float height = self.view.frame.size.height;
  6. <span style="white-space:pre"> </span>CGRect frame = CGRectMake(0.0f, -216,width,height);
  7. <span style="white-space:pre"> </span>//self.view整體上移216,其實就是把origin負向偏移
  8. <span style="white-space:pre"> </span>[UIView beginAnimations:@"ResizeView" context:nil];
  9. <span style="white-space:pre"> </span>[UIView setAnimationDuration:animationDuration];
  10. <span style="white-space:pre"> </span>self.view.frame = frame;
  11. [UIView commitAnimations];
  12. }

  1. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  2. {//當用戶按下ruturn,把焦點從textField移開那麼鍵盤就會消失了
  3. <span style="white-space:pre"> </span>NSTimeInterval animationDuration = 0.30f;
  4. float width = self.view.frame.size.width;
  5. float height = self.view.frame.size.height;
  6. CGRect frame = CGRectMake(0.0f,0.0f,width,height);
  7. //self.view移回原位置
  8. [UIView beginAnimations:@"ResizeView" context:nil];
  9. [UIView setAnimationDuration:animationDuration];
  10. self.view.frame = frame;
  11. [UIView commitAnimations];
Copyright © Linux教程網 All Rights Reserved