iphone - 当键盘覆盖事件的 UITextField 时 UIScrollView 不滚动(使用苹果的例子)

标签 iphone objective-c animation

我是 iOS 编程的新手,在编辑被键盘遮挡的 UITextField 时,我无法移动 UIScrollView。代码直接出Apple's documentation但由于某种原因它不起作用。

通过调试我发现通知似乎被正确传递(即它记录“ View 应该调整大小”,但仅当 activeField 是键盘下方的文本字段时)并且滚动点设置正确,但是scrollview 还是不动。另外,我有理由相信委托(delegate)模式是正确的(ViewController 是 textFields 和 scrollView 的委托(delegate))

- (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];
    NSLog(@"%@",@"view should resize");
}
}

鉴于代码直接来自文档,我可能只是遗漏了一些简单的东西。谁能指出我要检查的方向?

最佳答案

Apple 的示例有一个错误,它没有明确设置 ScrollView 的内容大小,因此使用默认内容大小 (0, 0)。我通过在我的 View Controller 中添加这段代码解决了这个问题:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set the scroll view's content size to be the same width as the
    // application's frame but set its height to be the height of the
    // application frame minus the height of the navigation bar's frame
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    CGRect navigationFrame = [[self.navigationController navigationBar] frame];
    CGFloat height = applicationFrame.size.height - navigationFrame.size.height;
    CGSize newContentSize = CGSizeMake(applicationFrame.size.width, height);

    ((UIScrollView *)self.view).contentSize = newContentSize;
}

关于iphone - 当键盘覆盖事件的 UITextField 时 UIScrollView 不滚动(使用苹果的例子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8528134/

相关文章:

javascript - 绘制多个对象时,processingjs 闪烁

ios - 如何从我的 iPhone 向 Apple 电视应用程序发送数据

iphone - 还有其他人在已发布的 IOS 5 上安装 iPhone Enterprise 应用程序时遇到问题吗?

objective-c - 计算两个 CGPoint 之间距离的最快方法?

iphone - 我需要显式分配我的 NSNumber 吗?

java - Vaadin 动画,使用 Valo 主题淡出和隐藏

ios - iOS (iPhoneX) 上的 html5 视频播放

iphone - 当我按下计算器中的任何数字按钮时,iOS 模拟器会生成错误

ios - 在 objective-C 中比较 ios 中的多个图像

css - animate.css - 1 个 div 上的 2 个类