我有一个视图的应用程序,从视图的顶部到视图的底部都有文本字段。我需要它在编辑底部字段时滚动,以便字段可见,但它似乎不能正常工作。键盘在活动文本字段上滚动 - 滚动到视图外?
继Apple docs后,我把所有的代码放到我的程序中(清单4-1,4-2),并将scrollView
和activeField
插座添加到我的头文件并将它们链接到IB。
问题是,只要我点击一个文本字段,所有的文本字段都会熄灭,直到我关闭键盘。他们向下滚动很远(再次,远远没有任何字段可见)。
有谁知道可能会导致什么问题?
我将代码放在Apple Docs的这里,以便您可以确切地看到我使用的代码,而无需点击。
//my .h
IBOutlet UIScrollView *scrollView;
IBOutlet UITextField *activeField;
//.m
// 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 application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
我编辑的苹果代码的拷贝 - 粘贴了您的文章,因为它是值得怀疑的SO具有从苹果授权复制它。我还标示让主持人看一看 - 我不确定官方政策是或应该是什么。 –
@Josh:对于[[合理使用]](http://en.wikipedia.org/wiki/Fair_use)目的而言,少量代码可能是正确的。 –
@罗伯特:好的,谢谢。詹姆斯,我想这意味着如果你愿意,你应该把它放回去。对不起,麻烦了。 –