zoukankan      html  css  js  c++  java
  • 【源码】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  
    效果如下:



     
  • 相关阅读:
    jquery 中 $.map 的使用方法
    数据库 'MessageManage' 的事务日志已满。若要查明无法重用日志中的空间的原因,请参阅 sys.databases 中的 log_reuse_wait_desc 列。
    Post提交
    MD5加密、时间戳转换、base64算法加密、解密
    C#中timer类的用法
    软件项目版本号的命名规则及格式
    SQL Server数据库脚本备份与还原
    C# Out,Ref 学习总结
    在线工具
    构造和析构 的顺序
  • 原文地址:https://www.cnblogs.com/wangbinios/p/8431717.html
Copyright © 2011-2022 走看看