我有一個視圖的應用程序,從視圖的頂部到視圖的底部都有文本字段。我需要它在編輯底部字段時滾動,以便字段可見,但它似乎不能正常工作。鍵盤在活動文本字段上滾動 - 滾動到視圖外?
繼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)目的而言,少量代碼可能是正確的。 –
@羅伯特:好的,謝謝。詹姆斯,我想這意味着如果你願意,你應該把它放回去。對不起,麻煩了。 –