项目开发中文本框输入的时候经常会用到键盘弹框遮挡的问题。解决办法就是根据底部键盘弹出的高度动态的改变对应view的位置。这里以多行文本框输入为例,效果图如下。
//第一步,注册监听键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
//第二步,根据通知调整对应view的位置
#pragma mark - 键盘的通知
- (void)keyboardShow:(NSNotification *)notify
{
//获取键盘弹框的位置信息
CGRect keyBoardRect = [notify.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat deltaY = keyBoardRect.size.height/2;
//添加动画效果,向上偏移键盘高度的二分之一
[UIView animateWithDuration:[notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
self.bottomView.transform = CGAffineTransformMakeTranslation(0, -deltaY);
}];
}
- (void)keyboardHide:(NSNotification *)note
{
//位置还原
[UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
self.bottomView.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished){
}];
}
//第三步,不用的时候移除掉通知对象
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}