我有一个滚动视图上有几个文本字段的表单。我试图解决键盘隐藏一些文本字段的问题,我部分做到了。至少当我点击每个单独的字段时效果很好。我使用了推荐的 Apple 方法:
我已经在 viewDidLoad 中注册了键盘通知:
[[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];
我正在跟踪活动文本字段:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
activeTextField = nil;
}
当键盘出现时,我正在向上滚动视图:
- (void)keyboardWillShow:(NSNotification *)aNotification {
// Get the size of the keyboard
NSDictionary* info = [aNotification userInfo];
keyboardHeight = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardHeight + 44 + 44; // Compensates for Navbar and text field height
if (!CGRectContainsPoint(aRect, activeTextField.frame.origin) ) {
[scrollView scrollRectToVisible:activeTextField.frame animated:YES];
}
}
然后,当键盘隐藏时,我将视图滚动回默认值(我不会粘贴代码,因为它工作正常)。
但是,在我的 5 个文本字段中,前 4 个在键盘上有一个 Next 按钮(而不是 Return),而最后一个字段有 Done。这个想法是我希望用户从一个文本字段跳转到另一个文本字段(在我的情况下,一个方向就足够了)。所以,我也实现了一个 UITextField 委托方法来处理它:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == firstNameTextField) {
[lastNameTextField becomeFirstResponder];
} else if (textField == lastNameTextField) {
[countryTextField becomeFirstResponder];
} else if (textField == cityTextField) {
[zipCodeTextField becomeFirstResponder];
} else if (textField == zipCodeTextField) {
[zipCodeTextField resignFirstResponder];
}
return NO;
}
上面的中间文本字段被跳过,因为对于该文本字段,我使用了不同的输入类型(带有 UIPickerView 的自定义视图和顶部带有 Next 按钮的栏) - 缺少的代码在此方法中:
- (IBAction)goToNextTextField:(id)sender {
[cityTextField becomeFirstResponder];
}
好的,正如我已经提到的,即使键盘尺寸(标准 iOS 与我的自定义视图)的高度不同,在点击单个文本字段(然后关闭键盘)时视图调整效果很好。我还可以通过点击下一步按钮成功浏览所有文本字段。
这是我的问题:
- 当点击 Next 时,如果键盘没有改变(例如,从字段 4 到 5,两者都使用标准键盘),我的 keyboardWillShow: 方法没有被调用,NSLog 调试器将 keyboardHeight 显示为 0,但视图却不可预测地向上移动。
- 此外,当在字段 3(使用自定义输入视图的字段)之间导航时,不会重新计算键盘高度。我已经尝试注册到 UIKeyboardDidChangeFrameNotification 和 UIKeyboardWillChangeFrameNotification (指向keyboardWillShow:方法),但没有多大成功。值得注意的是,我确实在控制台中看到了keyboardHeight 正在发生变化,但它通常滞后一步,即keyboardHeight 在我离开现场时更新,而不是在它成为FirstResponder 时更新。
也许一双有经验的眼睛会发现我的错误,因为过去两天我一直在摧毁我的一双眼睛寻找解决方案。
谢谢!