Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect UIScrollview bottom reached

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

like image 509
lubilis Avatar asked Dec 14 '13 13:12

lubilis


5 Answers

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
}}
like image 197
ytbryan Avatar answered Nov 11 '22 13:11

ytbryan


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
        }
    }
like image 30
ingconti Avatar answered Nov 11 '22 13:11

ingconti


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView 
{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height) 
    {
        // we are at the end
    }
}
like image 7
Proveme007 Avatar answered Nov 11 '22 13:11

Proveme007


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
   }
}
like image 4
Carlos Perez Perez Avatar answered Nov 11 '22 15:11

Carlos Perez Perez


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.

like image 2
Ed Liss Avatar answered Nov 11 '22 13:11

Ed Liss