有时候搞开发会碰到一个问题,就是当点击一个UITextField时,弹出虚拟键盘会将这个文本控件遮住。这无论从开发角度还是用户体验来说,都是不行的。
其实要解决这个问题也是很简单的,只要获取键盘没弹出前键盘的Rect,键盘弹出后键盘的Rect,其实最主要的变化还是在于Y值嘛,所以只要两者相减就
能得到需要移动的距离,然后做个动画就OK了。
那具体代码如下:
- #import "ViewController.h"
- @interface ViewController ()
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- //注册观察键盘的变化
- [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];
- }
- //键盘回收
- -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
- {
- for(UIView *view in self.view.subviews)
- {
- [view resignFirstResponder];
- }
- }
- //移动UIView
- -(void)transformView:(NSNotification *)aNSNotification
- {
- //获取键盘弹出前的Rect
- NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
- CGRect beginRect=[keyBoardBeginBounds CGRectValue];
- //获取键盘弹出后的Rect
- NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
- CGRect endRect=[keyBoardEndBounds CGRectValue];
- //获取键盘位置变化前后纵坐标Y的变化值
- CGFloat deltaY=endRect.origin.y-beginRect.origin.y;
- NSLog(@"看看这个变化的Y值:%f",deltaY);
- //在0.25s内完成self.view的Frame的变化,等于是给self.view添加一个向上移动deltaY的动画
- [UIView animateWithDuration:0.25f animations:^{
- [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)];
- }];
- }
- @end
转载自:http://blog.csdn.net/qq_27325349/article/details/51035877