【问题标题】:UIScrollView not scrolling when keyboard covers active UITextField (Using apple's example)键盘覆盖活动 UITextField 时 UIScrollView 不滚动(使用苹果的示例)
【发布时间】:2011-12-15 23:39:38
【问题描述】:

我是 iOS 编程新手,在编辑被键盘遮挡的 UITextField 时,我无法让 UIScrollView 移动。该代码直接来自Apple's documentation,但由于某种原因无法正常工作。

通过调试,我发现通知似乎已正确传递(即它记录“视图应调整大小”,但仅当 activeField 是键盘下方的 textField 时)并且滚动点设置正确,但滚动视图仍然不动。另外,我有理由确定委托模式是正确的(ViewController 是 textFields 和 scrollView 的委托)

- (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");
}
}

由于代码直接来自文档,我可能只是缺少一些简单的东西。谁能指出我要检查的事情的方向?

【问题讨论】:

标签: iphone objective-c animation


【解决方案1】:

Apple 的示例有一个错误,它没有明确设置滚动视图的内容大小,因此使用了默认的内容大小,即 (0, 0)。我通过在我的视图控制器中添加此代码解决了这个问题:

- (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;
}

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 2015-11-13
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多