【发布时间】:2011-07-27 12:38:34
【问题描述】:
当用户开始编辑 UITextField 并且文本字段被键盘隐藏时,我正在尝试使 UIScrollView 滚动。我正在使用来自以下线程的示例。
How to make a UITextField move up when keyboard is present
我的视图中有四个 UITextField。第一次显示键盘时,视图不会自动滚动。如果我在显示键盘的情况下单击另一个文本字段,则 UIScrollView 会按预期滚动。 隐藏键盘(通过点击“完成”按钮)并再次点击 UITextField 会出现同样的问题:UIScrollView 起初不会滚动,但将焦点更改为另一个文本字段时,它会完美滚动。
谁能帮帮我?
在viewDidLoad我设置了scrollView的大小
keyboardIsShown = NO;
CGSize scrollContentSize = CGSizeMake(320, 350);
self.scrollView.contentSize = scrollContentSize;
我在viewWillAppear注册了键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:self.view.window];
然后我在viewWillDisappear注销
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
通知调用以下两个方法。
- (void)keyboardWillShow:(NSNotification *)n {
if (keyboardIsShown) {
return;
}
NSDictionary *userInfo = [n userInfo];
NSValue *boundsValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [boundsValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= (keyboardSize.height - 50);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
[self.scrollView setFrame:viewFrame];
[UIView commitAnimations];
keyboardIsShown = YES;
}
- (void)keyboardWillHide:(NSNotification *)n {
NSDictionary *userInfo = [n userInfo];
NSValue *boundsValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [boundsValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height += (keyboardSize.height - 50);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
[self.scrollView setFrame:viewFrame];
[UIView commitAnimations];
keyboardIsShown = NO;
}
【问题讨论】:
-
你好,如果你想在你的“keyboardWillHide:”方法中获取键盘高度,键盘高度是 0 吗?您是否在方法中设置了断点,以便查看程序是否进入该方法?
-
keyboardWillHide中的键盘高度为216。keyboardWillShow在键盘第一次出现时调用,keyboardWillHide在键盘关闭时正确调用。
标签: iphone sdk keyboard uiscrollview uitextfield