问题的描述:Bug with Keyboard on iPad in Landscape
我是在iPhone上发现这个问题的,在带有TextField的SCLAlertView显示时,点击TextField弹出键盘后,SCLAlertView并不会向上移动,而取消键盘后,SCLAlertView向下移动。
这样就会导致用户输入被键盘覆盖的问题,用户体验不是很好。
原因:
SCLAlerView.m中,注册监听了KeyBoard的事件:
- (void)addObservers
{
if(_canAddObservers)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
_canAddObservers = NO;
}
}
我们来看看keyboardWillShow,keyboardWillHide分别做了什么事情:
- (void)keyboardWillShow:(NSNotification *)notification
{
if(_keyboardIsVisible) return;
[UIView animateWithDuration:0.2f animations:^{
CGRect f = self.view.frame;
f.origin.y -= KEYBOARD_HEIGHT + PREDICTION_BAR_HEIGHT;
self.view.frame = f;
}];
_keyboardIsVisible = YES;
}
- (void)keyboardWillHide:(NSNotification *)notification
{
if(!_keyboardIsVisible) return;
[UIView animateWithDuration:0.2f animations:^{
CGRect f = self.view.frame;
f.origin.y += KEYBOARD_HEIGHT + PREDICTION_BAR_HEIGHT;
self.view.frame = f;
}];
_keyboardIsVisible = NO;
}
看上去非常正确,如果键盘出现,就调整y坐标的位置,上移SCLAlertView,键盘消失,就取消之前调整的位置。
但奇怪的就是,有时候,keyboardWillShow调用完成之后,系统调用了viewWillLayoutSubviews方法,而这里面又初始化SCLAlertView的位置居中:
// Set new main frame
CGRect r;
if (self.view.superview != nil) {
// View is showing, position at center of screen
r = CGRectMake((sz.width-_windowWidth)/2, (sz.height-_windowHeight)/2, _windowWidth, _windowHeight);
} else {
// View is not visible, position outside screen bounds
r = CGRectMake((sz.width-_windowWidth)/2, -_windowHeight, _windowWidth, _windowHeight);
}
self.view.frame = r;
这导致之前为了上移而调整的y坐标变回了句中,而keyboardWillHide调用之后,却没有触发viewWillLayoutSubviews,因此导致键盘消失后,SCLAlertView的位置下调。
既然不能阻止viewWillLayoutSubviews的调用,只能在他里面做下控制。修改:
// Set new main frame
CGRect r;
if (self.view.superview != nil) {
// View is showing, position at center of screen
r = CGRectMake((sz.width-_windowWidth)/2, (sz.height-_windowHeight)/2, _windowWidth, _windowHeight);
} else {
// View is not visible, position outside screen bounds
r = CGRectMake((sz.width-_windowWidth)/2, -_windowHeight, _windowWidth, _windowHeight);
}
if (_keyboardIsVisible) {
r.origin.y -= KEYBOARD_HEIGHT + PREDICTION_BAR_HEIGHT;
}
self.view.frame = r;
网友评论