以前使用IQKeyboardManager没遇到过什么问题,用它主要是为了解决2个问题:
1、点击TextField或者TextView等输入框控件的时候,视图可以自动弹到键盘上面,确保输入框不会被键盘挡住。
2、点击外部可以关闭键盘。
简单方便几行代码,一次性解决所有此类问题:
// 启用
[IQKeyboardManager sharedManager].enable=YES;
// 键盘上面多一个toolbar,可以显示placeHolder,还有快捷地在多个输入框之间切换,还有“Done”按钮,以免虚拟键盘上的“Return”有其他用途的时候,没有关闭键盘的按钮
[IQKeyboardManager sharedManager].enableAutoToolbar=YES;
// 一行代码配置好:外部点击关闭键盘
[IQKeyboardManager sharedManager].shouldResignOnTouchOutside=YES;
// 本文重点,问题所在
[IQKeyboardManager sharedManager].canAdjustTextView=YES;
先看图:
上图总共2个输入框,第一个是单行的textField,没有什么问题。
第二个是多行的IQTextView,也就是一个支持PlaceHolder的UITextView。键盘弹起的时候,这个输入框下面的部分总是被键盘挡住。
怎么办呢?
发现有canAdjustTextView这个配置,也就是上面代码的最后一行,看GitHub上作者的解释,觉得这个应该是TextView高度过大的时候,这个参数可以修复我们上面的问题。但是我配置了,没有起到作用。
那多大的高度算大呢?假设:
ScreenHeight = 手机高度
KbHeight = 键盘高度
NavAndStatusHeight = 导航栏和状态栏加起来的高度
TextViewHeight = TextView的高度
那么 (TextViewHeight > ScreenHeight - KbHeight - NavAndStatusHeight) 的时候,textView的高度就过大了,也就是键盘弹起的时候
TextViewHeight - (ScreenHeight - KbHeight - NavAndStatusHeight )的部分会被键盘遮挡。
IQKeyboardManager最多只会把输入框的顶部提到跟导航栏底部对齐,不会再高了。
那如何快速地解决这个问题呢?
目前临时方案是:
@weakify(textView, lineView, view)
//[[textView rac_textSignal] subscribeNext:^(id x) {
//[[IQKeyboardManager sharedManager] reloadLayoutIfNeeded];
//}];
//增加监听,当键盘出现或者改变时
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShow Notificationobject:nil]
subscribeNext:^(NSNotification*notification) {
CGSize kbSize;
//Getting UIKeyboardSize.
CGRect kbFrame = [[notificationuserInfo][UIKeyboardFrameEndUserInfoKey]CGRectValue];
CGRect screenSize = [[UIScreenmainScreen]bounds];
CGRect intersectRect =CGRectIntersection(kbFrame, screenSize);
if(CGRectIsNull(intersectRect))
{
kbSize =CGSizeMake(screenSize.size.width,0);
}
else
{
kbSize = intersectRect.size;
}
float height = screenSize.size.height- kbSize.height-kNavigationAndStatusBarHeight-20;
if(height > textView.mj_h) {
return;
}
@strongify(textView, view)
if(view ==nil)
{
return;
}
[textView remakeConstraints:^(MASConstraintMaker*make) {
make.right.left.top.equalTo(view);
make.height.equalTo(height);
}];
[[IQKeyboardManager sharedManager]reloadLayoutIfNeeded];
}];
////增加监听,当键盘退出时收出消息
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillHide Notificationobject:nil]
subscribeNext:^(idx) {
@strongify(textView, lineView, view)
if(view ==nil) {
return;
}
[UIView animateWithDuration:0.1animations:^{
[textView remakeConstraints:^(MASConstraintMaker*make) {
make.top.left.right.equalTo(view);
make.bottom.equalTo(lineView.top);
}];
[textView layoutIfNeeded];
[[IQKeyboardManager sharedManager]reloadLayoutIfNeeded];
}];
}];
监听键盘弹起和关闭事件,动态调整TextView的高度,使得TextView的顶部不会超过导航栏底部,就可以了。
有人知道更好的办法吗?请不离赐教。