我有一个基于视图的应用程序,在其中一个子视图中有一个UIScrollView。当键盘出现和消失时,我编写了处理程序来调整滚动视图的大小。我想在用户离开视图时关闭键盘,因此我在[currentField resignFirstResponder]
中拨打viewWillDisappear
。这解雇了键盘,但没有调用处理程序来调整滚动视图的大小(当我在其他地方调用相同的代码时,它会这样做)。有什么建议吗?
编辑:这些是我使用的处理程序:
-(void) keyboardWasShown:(NSNotification*) notification
{
if(keyboardShown)
return;
NSDictionary* info=[notification userInfo];
NSValue* value=[info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize=[value CGRectValue].size;
CGRect viewFrame=[scrollView frame];
viewFrame.size.height-=keyboardSize.height;
scrollView.frame=viewFrame;
keyboardShown=YES;
}
-(void) keyboardWasHidden:(NSNotification*) notification
{
NSDictionary* info=[notification userInfo];
NSValue* value=[info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize=[value CGRectValue].size;
CGRect viewFrame=[scrollView frame];
viewFrame.size.height+=keyboardSize.height;
scrollView.frame=viewFrame;
keyboardShown=NO;
}
当我在其他任何地方调用[currentField resignFirstResponder]
时,它会毫无问题地调用处理程序。
答案 0 :(得分:0)
所以你在发布UIKeyboardDidHideNotification
之前被视为观察者被移除,很高兴我能提供帮助。但观察UIKeyboardWillHideNotification
和UIKeyboardWillShowNotification
可能足以让您对键盘做出反应。键盘通知具有用户信息键UIKeyboardAnimationDurationUserInfoKey
,您可以使用键盘动画为帧调整设置动画。如果您不将它们设置为新位置,这可以避免您的观点会产生“笨拙”的感觉。以下是您可以做的快速示例:
-(void)keyboardWillNotificationTarget:(NSNotification *)note{
// Find current keyboard origin Y
NSValue *keyboardCurrentFrameValue = [note.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGFloat currentOriginY = keyboardCurrentFrameValue.CGRectValue.origin.y;
// Find keyboard Y that will be
NSValue *keyboardNewFrameValue = [note.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat newOriginY = keyboardNewFrameValue.CGRectValue.origin.y;
// Calculate new frame for scrollView
CGFloat heightChangeForScrollView = newOriginY - currentOriginY;
CGRect svFrame = scrollView.frame;
svFrame.size.height += heightChangeForScrollView;
// Find duration of animation
NSNumber *animationDurationNumber = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
CGFloat animationDuration = animationDurationNumber.floatValue;
// Animate scrollView with keyboard
[UIView animateWithDuration:animationDuration animations:^{
scrollView.frame = svFrame;
}];
}
现在您只需将此方法添加为两个通知的目标:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillNotificationTarget:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillNotificationTarget:) name:UIKeyboardWillHideNotification object:nil];