Detect UIScrollview bottom reached

2019-03-26 04:29发布

I have a UIScrollView with images and when the user scrolls to the end of the scrollview i want to update the content. This is my code to detect when the bottom of the scrollview is reached:

The code below is implemented in scrollViewDidScroll: delegate

CGFloat scrollViewHeight = imagesScrollView.bounds.size.height;
CGFloat scrollContentSizeHeight = imagesScrollView.contentSize.height;
CGFloat bottomInset = imagesScrollView.contentInset.bottom;
CGFloat scrollViewBottomOffset = scrollContentSizeHeight + bottomInset - scrollViewHeight;

if(imagesScrollView.contentOffset.y > scrollViewBottomOffset){


    [imagesView addSubview:imagesBottomLoadingView];

    [self downloadImages];

}

My problem is that when the user scrolls to bottom, my function is called several times, but i want to call it only once. I tried with imagesScrollView.contentOffset.y == scrollViewBottomOffset but it doesn't work and the function is not called

6条回答
走好不送
2楼-- · 2019-03-26 04:41

Sometimes you will have to use +1 in the condition because the contentSize.height gives you a few decimals over, so if you use this, you avoid it...

override func scrollViewDidScroll(scrollView: UIScrollView) {

   if (scrollView.contentOffset.y + 1) >= (scrollView.contentSize.height - scrollView.frame.size.height) {
       //bottom reached
   }
}
查看更多
做个烂人
3楼-- · 2019-03-26 04:49

Have you thought of adding a boolean. update it when the method is called for the first time and maybe when user scrolls back up.

查看更多
爷、活的狠高调
4楼-- · 2019-03-26 04:55

If you want to detect them in swift:

override func scrollViewDidScroll(scrollView: UIScrollView) {

if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
    //reach bottom
}

if (scrollView.contentOffset.y < 0){
    //reach top
}

if (scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y < (scrollView.contentSize.height - scrollView.frame.size.height)){
    //not top and not bottom
}}
查看更多
smile是对你的礼貌
5楼-- · 2019-03-26 05:02

Carlos answer is better.

For Swift 4.x you must change method name:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if (scrollView.contentOffset.y + 1) >= (scrollView.contentSize.height - scrollView.frame.size.height) {
            //bottom reached
        }
    }
查看更多
叛逆
6楼-- · 2019-03-26 05:04

implement scrollViewDidScroll: and check contentOffset in that for reaching the end

查看更多
爷、活的狠高调
7楼-- · 2019-03-26 05:07
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView 
{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height) 
    {
        // we are at the end
    }
}
查看更多
登录 后发表回答