如何在 scrollViewDidScroll 中添加一个 UIView 并使其滚动到最后?

How to add a UIView in scrollViewDidScroll and enable it to scroll till the end?

我在 UIScrollView 的末尾添加一个 UIView 如下 -

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

这在末尾添加了视图,但我无法滚动该视图。如何也启用滚动到新添加的视图?

可以设置scrollview的contentInset

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

但你可能不想在 - (void)scrollViewDidScroll:(UIScrollView *)scrollView 中添加子视图,因为这个函数会被多次调用,你的子视图会被创建很多次。 如果一定要在其中添加子视图,我建议你创建一个属性 paintView,并检查它是否为nil,如果是,则创建它,如果不是,则什么都不做

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

    }
}