弹出键盘,UIView 上移

声明

欢迎转载,但是请尊重作者劳动成果,转载请保留此框内声明,谢谢。 文章出处:http://blog.csdn.net/iukey

//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

默认情况下打开键盘会遮住下面的view,带来一点点困扰,不过这不是什么大问题,我们使用点小小的手段就可以解决。

首先我们要知道键盘的高度是固定不变的,不过在IOS 5.0 以后键盘的高度貌似不是216了,不过不要紧,我们调整调整就是了:

  iPhone ipad
竖屏(portrait) 216 264
横屏(landScape) 140 352

 

我们采取的方法就是在textField(有可能是其他控件)接收到弹出键盘事件时把self.view整体上移216px了(我们就以iPhone竖屏为例了)。

有关View的frame,origin,size之类的知识点不懂的请参看我的另一篇博文: <<有关View的几个基础知识点>>

//-----------------------------开始---------------------

先在 @interface 中 声明变量属性

@property (strong, nonatomic) IBOutlet UITextField *myTextField;

- (IBAction) returnKeyboard:(id) sender;

另外我们要设置textField的代理,我们就设为当前控制器了。

在viewDidLoad 中设置myTextField.delegate=self;

然后我们在当前控制器实现下面三个委托方法:

 

  1. - (void)textFieldDidBeginEditing:(UITextField *)textField  
  2. //当点触textField内部,开始编辑都会调用这个方法。textField将成为first responder   
  3.        NSTimeInterval animationDuration = 0.30f;      
  4.       CGRect frame = self.view.frame;
  5.    //如果屏幕已经上移过,就不上移。
  6.       if (frame.orign.y < 0){
  7.             return;
  8.       }  
  9.       frame.origin.y -=216;  
  10.       frame.size.height +=216;  
  11.       self.view.frame = frame;
  12.   
  13.        [UIView beginAnimations:@"ResizeView" context:nil];  
  14.        [UIView setAnimationDuration:animationDuration];
  15.   
  16.        self.view.frame = frame;                  
  17.        [UIView commitAnimations];                  
  18. }  

 

 
    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 不用写myTextField
    14. [textField resignFirstResponder;
    15. return YES;
    16. }

 

 

另外还需要写键盘返回动作,  需要把所有的 输入框  连接到 下面这个动作

- (IBAction)returnKeyboard:(id)sender

{

     [sender resignFirstResponder];

   如果是手写的界面就不需要下面,如果是拉的界面 就需要下面

 

在viewDidUnload中

     [self setMyTextField:nil];

posted @ 2013-09-21 09:47  李小见  阅读(1695)  评论(0编辑  收藏  举报