我有一个 UIViewController,我有一个 UIScrollView,里面有几个 UITextFields。我从苹果那里得到了一段代码,它似乎从键盘下方移动了内容。
- (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,因为我有一个导航栏。我的键盘也多了 44 个像素,因为我正在向它添加 UIToolBar,所以代码并没有真正工作。我尝试了各种配置来解决两个问题:
- 最后两个字段被 UIToolBar + 键盘覆盖,但只有最后一个触发 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];
}
}
UPDATE1:还有另一个错误,我在 UIToolBar 中有一个上一个按钮,如果我点击最后一个文本字段,滚动视图上升,如果我移回第一个文本视图,它在视图之外,因为滚动视图不会滚下来。