Need sample code to implement Paging Based UIScrol

2019-09-07 22:41发布

问题:

I am new to iOS development. Can anyone give me a working sample project/ tutorial of paging based scrollview? I need to load more data in my table view from a webservice as user scrolls down. I have spent a lot of time, but could not find anything that suits my need. Any help will be greatly appreciated.

I was able to figure out the solution of my problem. Now I am trying to detect scroll up and down based on the y offset difference. The problem is it always reads the drag to be downwards even if it is upward. This is how I am trying to detect the scroll direction:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    CGPoint scrollOffSet =  scrollView.contentOffset;
    NSLog(@"Current Content offset: , y = %f", scrollOffSet.y);
    NSLog(@"Previous offset , y = %f", self.previousYOffset);

    if(scrollOffSet.y > self.previousYOffset)
    {
        self.previousYOffset = scrollOffSet.y;
        NSLog(@"Scrolled Down");
        self.nextPageNumber++;
        //Here I send the request to fetch data for next page number
    }
    else {
        NSLog(@"Scrolled up");
        self.previousYOffset = scrollOffSet.y;
    }

}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{

    CGPoint scrollOffSet =  scrollView.contentOffset;
    NSLog(@"Current Content offset: y = %f", scrollOffSet.y);
}

The problem is: either i scroll up or down, it will always display "scrolled down", thus it goes to fetch data for next page number even if it was not intended to request. Plus, the y offset positions it returns on up/down scroll are also very confusing. Please guide me how to accurately detect an upside scroll?

回答1:

Do you mean a "swipable" UIScrollView?

Paging a UIScrollView is quite easy. First make sure you have the pagingEnabled property set to YES. The UIScrollView will use it's own frame as the size of a page (like a viewport).

Use the contentSize property to determine the scrollable area.

Example:

//scrollView is a UIScrollView instance  
int pageCount = 3;  
scrollView.pagingEnabled = YES;  
scrollView.contentSize = CGSizeMake(scrollView.frame.width*pageCount, scrollView.frame.height);