iOS鍵盤彈出的時候會擋住底部的控制元件,可以通過以下方法將整個UIView上移。
阿新 • • 發佈:2019-02-06
//通知中心addObserver
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];
//鍵盤迴收 -(void)touchesBegan:(NSSet *)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; //在0.25秒內完成self.view的Fram變化,等於是給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)]; }]; }