这篇文章主要为大家详细介绍了iOS键盘弹出遮挡输入框的解决方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文为大家分享了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);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:iOS键盘弹出遮挡输入框的解决方法
基础教程推荐
猜你喜欢
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- android studio按钮监听的5种方法实例详解 2023-01-12
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Android多返回栈技术 2023-04-15
- Android中的webview监听每次URL变化实例 2023-01-23
- Flutter手势密码的实现示例(附demo) 2023-04-11
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
