如何在scrollViewDidScroll中添加UIView并使其滚动直到结束?

时间:2015-08-31 22:37:49

标签: ios objective-c uiview uiscrollview

我在UIView的末尾添加UIScrollView,如下所示 -

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    float scrollViewHeight = scrollView.frame.size.height;
    float scrollContentSizeHeight = scrollView.contentSize.height;
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset == 0)
    {
    }
    else if (scrollOffset + scrollViewHeight >= scrollContentSizeHeight)
    {
        UIView *paintView=[[UIView alloc]initWithFrame:CGRectMake(0, scrollOffset + scrollViewHeight + 20, self.view.frame.size.width, 200)];
        [paintView setBackgroundColor:[UIColor yellowColor]];
        [self.containerScrollView addSubview:paintView];
    }
}

这最后添加了视图,但我无法滚动该视图。如何启用滚动到新添加的视图?

1 个答案:

答案 0 :(得分:2)

您可以设置scrollview的contentInset

scrollView.contentInset = UIEdgeInsetsMake(0,0,extensionHeight,0);

但你可能不想在- (void)scrollViewDidScroll:(UIScrollView *)scrollView中添加子视图,因为这个函数会被多次调用,你的子视图会被多次创建。 如果你必须在其中添加子视图,我建议你创建一个属性paintView,并检查它是否为零,如果是,则创建它,如果没有,只是不做任何事情

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    float scrollViewHeight = scrollView.frame.size.height;
    float scrollContentSizeHeight = scrollView.contentSize.height;
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset == 0)
    {
    }
    else if (scrollOffset + scrollViewHeight >= scrollContentSizeHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(0,0,extensionHeight,0);
        if (!_paintView) {
            _paintView=[[UIView alloc]initWithFrame:CGRectMake(0, scrollOffset + scrollViewHeight + 20, self.view.frame.size.width, 200)];
            [_paintView setBackgroundColor:[UIColor yellowColor]];
            [self.containerScrollView addSubview:_paintView];
        }

    }
}