Problem with scrollViewDidScroll delegate method a

2019-06-13 15:16发布

I have a scroll view and i am implementing lazyload with page control. I have taken the pagecontrol sample program by apple.

I load 8 thumbnails in every page and the thumbnails themselves are fetched from the network and updated on the UI. The image views are already present in the UI. In my viewDidScroll method i calculate the page number and then update the other pages above and below it as follows:

BOOL isScrollingDown = verticalScrollView.contentOffset.y > _previousContentOffsetY;

_previousContentOffsetY = verticalScrollView.contentOffset.y;

CGFloat pageHeight = verticalScrollView.frame.size.height;

int scrollingToPageNum = isScrollingDown ? (ceil((verticalScrollView.contentOffset.y - pageHeight) / pageHeight) + 1) : (floor((verticalScrollView.contentOffset.y - pageHeight) / pageHeight) + 1);
int page = floor((verticalScrollView.contentOffset.y - pageHeight / 2) / pageHeight) + 1;

[self loadPage:(page-1)];
[self loadPage:(page)];
[self loadPage:(page+1)];

/* Unloading the pages not seen in the view is done here*/
if (!(isScrollingDown) && scrollingToPageNum >1) {
    [self unloadPages:page-2];
}else {
    [self unloadPages:page+2];
}

The UI is too slow and the user experience is very bad. I want to know how can i make the UI more responsive.

Some other questions are: 1) I have a class which downloads the images and the calling class implements the delegate for the downloader class. Once the image is downloaded the delegate method is called to update the UI. Does this slow down the responsiveness of the UI? How can this be avoided? 2) What is a optimal way to implement downloading of images and updating the ui without having the UI become unresponsive?

EDIT: I am open to ideas on how to best improve and implement this solution. I am not creating a thread explicitly but i am using NSURLConnection in async mode, and when data is retrieved the delegate method is called to update the UI.

2条回答
唯我独甜
2楼-- · 2019-06-13 15:33

I think you could greatly benefit from some of the techniques used in the Apple sample LazyTableImages. While it uses a table view as an example, the concepts can easily be applied to a scroll view.

LazyTableImages

查看更多
Root(大扎)
3楼-- · 2019-06-13 15:36

You are calling loadPage multiple times every time scrollViewDidScroll gets called (at least, I assume you mean scrollViewDidScroll). What does loadPage do? If it blindly triggers off a comms request, no wonder your app is going crazy -- you will be requesting the same thing many times, in parallel -- scrollViewDidScroll will get called for every different offset you see of your scroll view.

Perhaps you should think about using a more appropriate delegate method such as scrollViewDidEndDecelerating: to orchestrate things. Mark Adam's answer is also very good advice.

This question and answer also explains the same problem:

My App calls scrollViewDidScroll 19 times

查看更多
登录 后发表回答