在我的应用中,表格很少。有时键盘隐藏字段,因此用户无法看到他键入的内容。在这种情况下,我找到了移动视图或滚动查看的方法,因此文本字段保持在键盘上方。 问题是在iPhone 5上我需要为最后3个文本字段移动视图,但对于iPhone 6 - 仅用于最后一个文本字段。
我可以定义所有字段和设备屏幕高度值的情况。 但是我想找到更优雅的解决方案来检测当前设备上的键盘下面的texfield是否需要移动视图?
答案 0 :(得分:0)
使用TPKeyboardAvoidingScrollView。它易于使用
将TPKeyboardAvoidingScrollView.m和TPKeyboardAvoidingScrollView.h源文件放入项目中,将UIScrollView弹出到视图控制器的xib中,将滚动视图的类设置为TPKeyboardAvoidingScrollView,并将所有控件放在该滚动视图中。您也可以在不使用xib的情况下以编程方式创建它 - 只需使用TPKeyboardAvoidingScrollView作为顶级视图。
答案 1 :(得分:0)
您需要收听
等键盘通知// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[self.scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
答案 2 :(得分:0)
您可以使用其委托方法UITextField
来检测哪个- (void)textFieldDidBeginEditing:(UITextField *)textField
是“有效”。
使用textField.frame
计算您需要为scrollView.contentOffset
设置的偏移量。
在- textFieldDidBeginEditing:
方法中,您可以重置contentOffset = CGPointZero