有时候搞开发会碰到一个问题,就是当点击一个UITextField时,弹出虚拟键盘会将这个文本控件遮住。这不管从开发角度仍是用户体验来讲,都是不行的。html
其实要解决这个问题也是很简单的,只要获取键盘没弹出前键盘的Rect,键盘弹出后键盘的Rect,其实最主要的变化仍是在于Y值嘛,因此只要二者相减就xcode
能获得须要移动的距离,而后作个动画就OK了。post
那具体代码以下:动画
- #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];
- }
- }
-
- -(void)transformView:(NSNotification *)aNSNotification
- {
-
- NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
- CGRect beginRect=[keyBoardBeginBounds CGRectValue];
-
-
- NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
- CGRect endRect=[keyBoardEndBounds CGRectValue];
-
-
- CGFloat deltaY=endRect.origin.y-beginRect.origin.y;
- NSLog(@"看看这个变化的Y值:%f",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
效果以下:

