您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
iOS中键盘弹出会遮挡输入框如何解决?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
解决思路:
监听键盘出现和消失的状态,当键盘出现时,当前视图上移,当输入完成收起键盘时,视图回到初始状态。
难点:视图向上平移的距离
原理都差不多,oc版参考代码:
self.phoneInput = [UITextField new]; self.phoneInput.placeholder = @"请输入..."; [self.view addSubview:self.phoneInput]; ///键盘弹出 处理遮挡问题 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; } - (void)keyboardWillShow:(NSNotification *)notification { //获取处于焦点中的view NSArray *textFields = @[self.phoneInput]; UIView *focusView = nil; for (UITextField *view in textFields) { if ([view isFirstResponder]) { focusView = view; break; } } if (focusView) { //获取键盘弹出的时间 double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; //获取键盘上端Y坐标 CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y; //获取输入框下端相对于window的Y坐标 CGRect rect = [focusView convertRect:focusView.bounds toView:[[[UIApplication sharedApplication] delegate] window]]; CGPoint tmp = rect.origin; CGFloat inputBoxY = tmp.y + focusView.frame.size.height; //计算二者差值 CGFloat ty = keyboardY- inputBoxY; NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty); //差值小于0,做平移变换 [UIView animateWithDuration:duration animations:^{ if (ty < 0) { self.view.transform = CGAffineTransformMakeTranslation(0, ty); } }]; } } - (void)keyboardWillHide:(NSNotification *)notification { //获取键盘弹出的时间 double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; //还原 [UIView animateWithDuration:duration animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, 0); }]; } ///<UITextFieldDelegate> ///UITextFieldDelegate编辑完成,视图恢复原状 -(void)textFieldDidEndEditing:(UITextField *)textField { self.view.frame =CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height); }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。