键盘遮挡输入框处理
Posted 湘岳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了键盘遮挡输入框处理相关的知识,希望对你有一定的参考价值。
1.定义一个记录光标底部的成员变量cursorBottom
2.监听键盘出现和键盘消失通知(记得在dealloc方法中 移除监听器)
3.在UITextField的代理方法textFieldShouldBeginEditing:中转换当前输入框的原点坐标到scrollView中的坐标,计算光标底部坐标并保存
4.在监听键盘出现执行方法中计算 需不需要滚动及滚动大小,动画实现滚动
5.在监听键盘消失方法和点击空白处方法,关闭键盘
主要实现代码如下:
@interface AddAccountViewController ()<UITextFieldDelegate>
@property (nonatomic, assign) CGFloat cursorBottom;
@end
@implementation AddAccountViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
self.scrollView.backgroundColor = self.view.backgroundColor;
[self.scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard)]];
[self.view addSubview:self.scrollView];
//注册键盘出现的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
//注册键盘消失的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:nil];
[self setupAccountInfo];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
CGPoint point = [textField convertPoint:CGPointMake(0, 0) toView:_scrollView];
self.cursorBottom = textField.height+point.y ;
return YES;
}
#pragma mark 键盘代理事件
///键盘显示事件
- (void) keyboardWillShow:(NSNotification *)notification {
//获取键盘高度,在不同设备上,以及中英文下是不同的
CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
//计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
CGFloat offset = self.cursorBottom + kbHeight - self.view.height;
// 取得键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//将视图上移计算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.scrollView.contentOffset = CGPointMake(0, offset);
}];
}
}
///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
// 键盘动画时间
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//视图下沉恢复原状
[UIView animateWithDuration:duration animations:^{
self.scrollView.contentOffset = CGPointMake(0, 0);
}];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (void)hiddenKeyboard
{
[self.view endEditing:YES];
}
@end
以上是关于键盘遮挡输入框处理的主要内容,如果未能解决你的问题,请参考以下文章