有時候搞開發會碰到一個問題,就是當點擊一個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
效果以下: