【发布时间】:2014-10-31 12:10:24
【问题描述】:
我正在使用 6.1 模拟器测试我的 iOS 应用程序。当键盘可见时(在用户单击 textView 之后),我已经工作了几个小时将我的 scrollView 滚动到正确的位置。我已尝试按照此页面上标记为正确的答案进行操作:
How do I scroll the UIScrollView when the keyboard appears?
这是我目前拥有的:
- (void)keyboardWasShown:(NSNotification*)aNotification {
NSLog(@"keyboardWasShown");
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.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, self.activeView.frame.origin) ) {
NSLog(@"scrollToView");
CGPoint scrollPoint = CGPointMake(0.0, self.stepDescriptionField.frame.origin.y-kbSize.height);
NSLog(@"scrollPoint: %f", scrollPoint.y);
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
从上图可以看出,如果用户点击textView,scrollView并没有滚动到正确的位置(应该可以看到textView的文本内容)。
奇怪的是,我手动尝试将 scrollPoint 的 y 偏移更改为不同的值,但它似乎对窗口滚动到的位置没有影响。 我做错了什么?
其他可能很重要的事情:
- 我已关闭自动布局(以便用户可以在此视图中垂直滚动)。
- textView 不可滚动(已调整大小以适合其内容)
编辑
我发现如果我将我的偏移量添加到 contentInsets 如下:
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+50.0, 0.0);
视图将滚动到正确的位置。唯一的缺点是底部有额外的填充:
有没有更好的方法来做到这一点?
【问题讨论】:
标签: ios objective-c uiscrollview keyboard