我正在编写一个针对 iOS 6.1 的应用程序。如果 UITextField 被键盘遮挡,我正在尝试遵循这个Apple 文档,了解如何将它滚动到视图中。问题是 Apple 记录的用于计算滚动点的算法效果不佳。我计算滚动点的算法效果稍好一些,但相差 70 像素。计算滚动点的正确方法是什么?
下面你可以看到,从左到右,我的键盘显示之前的视图,滚动后的视图使用Apple的算法计算滚动点,滚动后的视图使用我的算法计算滚动点。(该网格中的每个正方形都是 25 像素 x 25 像素。)
这是我正在使用的代码。注意#if APPLE_WAY
块。
- (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);
self.view.contentInset = contentInsets;
self.view.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, self.activeField.frame.origin) ) {
#if APPLE_WAY
CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-kbSize.height);
#else
CGFloat offset = self.activeField.frame.origin.y;
//TODO: Why is this off by 70?
offset = offset - 70;
CGPoint scrollPoint = CGPointMake(0.0, offset);
#endif
[self.view setContentOffset:scrollPoint animated:YES];
}
}