UIViewController を取得し、内部にいくつかの UITextFields を含む UIScrollView を取得しました。Apple から、キーボードの下からコンテンツを移動しているように見えるコードを入手しました。
- (void)keyboardWasShown:(NSNotification *)notification
{
// Step 1: Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Step 3: Scroll the target text field into view.
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardSize.height;
if (!CGRectContainsPoint(aRect, self.firstResponder.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, self.firstResponder.frame.origin.y - (keyboardSize.height-10));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
ナビゲーション バーがあるため、UIScrollView は 320x416 です。また、キーボードに UIToolBar を追加しているため、キーボードにさらに 44 ピクセルが追加されているため、コードは実際には機能していません。2 つの問題を解決するために、あらゆる種類の構成を試しました。
- 最後の 2 つのフィールドは UIToolBar + キーボードでカバーされていますが、最後の 1 つだけが UIScrollView の動きをトリガーします。
- UIScrollView が移動しているだけでなく、UIToolBar のために UITextField がまだキーボードの後ろにあります。
更新:これは機能しますが、間違っていると確信しています。正しい場合、理由がわからず、意味がありません。誰かがそれを修正/説明できますか?
- (void)keyboardWasShown:(NSNotification *)notification
{
// Step 1: Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 44.0f, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// Step 3: Scroll the target text field into view.
CGRect aRect = self.view.frame;
aRect.size.height -= keyboardSize.height + 44.0f;
if (!CGRectContainsPoint(aRect, self.firstResponder.frame.origin) ) {
CGPoint scrollPoint = CGPointMake(0.0, self.firstResponder.frame.origin.y - (keyboardSize.height-10.0f - 44.0f - 44.0f - 44.0f));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
更新 1:別のバグがあります。UIToolBar に前のボタンがあります。最後のテキスト フィールドをタップすると、スクロール ビューが上がります。最初のテキスト ビューに戻ると、ビューの外側になります。転がり落ちません。