iOS-監聽鍵盤輸入,視圖整體上移或恢複-避免輸入遮擋
1.初始化輸入框,監聽輸入框開始編輯和結束編輯
//密碼輸入框 UITextField *loginInputPasswordStr = [UITextField inputTextWithImage:[UIImage imageNamed:@"Password"] placeholderText:NSLocalizedString(@"Password", nil)]; loginInputPasswordStr.frame = RectMakeWithPercent(24/375.0, 385/667.0, 327/375.0, 48/667.0); //設定鍵盤類型 loginInputPasswordStr.keyboardType = UIKeyboardTypeDefault; //設定暗文 [loginInputPasswordStr setSecureTextEntry:YES]; //監聽密碼輸入框文字開始輸入 [loginInputPasswordStr addTarget:self action:@selector(loginInputPasswordStrInputBegin) forControlEvents:UIControlEventEditingDidBegin]; //監聽密碼輸入框文字結束輸入 [loginInputPasswordStr addTarget:self action:@selector(loginInputPasswordStrInputEnd) forControlEvents:UIControlEventEditingDidEnd]; [self.view addSubview:loginInputPasswordStr];
2.開始編輯時視圖上移,結束編輯或點擊螢幕時恢複初始位置.
//loginInputPasswordStr監聽方法-(void)loginInputPasswordStrInputBegin{ [self moveView];}-(void)loginInputPasswordStrInputEnd{ [self resumeView];}// 點擊螢幕取消輸入,恢複視圖初始位置-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; [self resumeView];}
3.主體方法!
#pragma mark - 點擊輸入框視圖整體上移/恢複//恢複原始視圖位置-(void)resumeView{ NSLog(@"恢複原始視圖位置之前self.view.origin.y :%f",self.view.origin.y); //當視圖上移130像素時-> if (self.view.frame.origin.y == -130) { NSTimeInterval animationDuration=0.40f; [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; [UIView setAnimationDuration:animationDuration]; //如果當前View是父視圖,則Y為20個像素高度,如果當前View為其他View的子視圖,則動態調節Y的高度 float fX = self.view.frame.origin.x; float fY = self.view.frame.origin.y + 130; float width = self.view.frame.size.width; float height = self.view.frame.size.height; //下移130個單位,按實際情況設定 self.view.frame = CGRectMake(fX, fY, width, height); [UIView commitAnimations]; }}// 移動視窗-(void) moveView{ NSLog(@"移動視窗之前self.view.origin.y :%f",self.view.origin.y); //只有當視圖在初始位置的時候-> if (self.view.origin.y == 0) { NSTimeInterval animationDuration=0.40f; [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; [UIView setAnimationDuration:animationDuration]; float fX = self.view.frame.origin.x; float fY = self.view.frame.origin.y - 130; float width = self.view.frame.size.width; float height = self.view.frame.size.height; //上移130個單位 self.view.frame = CGRectMake(fX, fY, width, height); [UIView commitAnimations]; }}