【源码】iOS之键盘弹出视图上移

有时候搞开发会碰到一个问题,就是当点击一个UITextField时,弹出虚拟键盘会将这个文本控件遮住。这无论从开发角度还是用户体验来说,都是不行的。

其实要解决这个问题也是很简单的,只要获取键盘没弹出前键盘的Rect,键盘弹出后键盘的Rect,其实最主要的变化还是在于Y值嘛,所以只要两者相减就

能得到需要移动的距离,然后做个动画就OK了。

那具体代码如下:

  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewController  
  8.   
  9. - (void)viewDidLoad  
  10. {  
  11.     [super viewDidLoad];  
  12.       
  13.     //注册观察键盘的变化  
  14.     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];  
  15.       
  16. }  
  17. //键盘回收  
  18. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event  
  19. {  
  20.     for(UIView *view in self.view.subviews)  
  21.     {  
  22.         [view resignFirstResponder];  
  23.     }  
  24. }  
  25.   
  26. //移动UIView  
  27. -(void)transformView:(NSNotification *)aNSNotification  
  28. {  
  29.     //获取键盘弹出前的Rect  
  30.     NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];  
  31.     CGRect beginRect=[keyBoardBeginBounds CGRectValue];  
  32.       
  33.     //获取键盘弹出后的Rect  
  34.     NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];  
  35.     CGRect  endRect=[keyBoardEndBounds CGRectValue];  
  36.       
  37.     //获取键盘位置变化前后纵坐标Y的变化值  
  38.     CGFloat deltaY=endRect.origin.y-beginRect.origin.y;  
  39.     NSLog(@"看看这个变化的Y值:%f",deltaY);  
  40.       
  41.     //在0.25s内完成self.view的Frame的变化,等于是给self.view添加一个向上移动deltaY的动画  
  42.     [UIView animateWithDuration:0.25f animations:^{  
  43.         [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+deltaY, self.view.frame.size.width, self.view.frame.size.height)];  
  44.     }];  
  45. }  
  46. @end  
效果如下:



 
posted @ 2018-02-08 15:25  王彬iOS  阅读(852)  评论(0编辑  收藏  举报