iosiphonepaginationuiscrollviewuiimageview

ios uiscrollview with pagingenabled between uiimageviews how to detect which one is on the screen/visible


So I have a UIScrollview that scrolls horizontally with paging through a bunch of different UIImageViews containing user avatars. But, I want to only load the avatars from their URL IFF they are actually showing on the screen (4 are showing at a time, but I can scroll through like 30 or more or less). Is there a way of detecting which UIImageView/ which page it is on? Or does anyone have any general recommendations or ideas for how I should go about this problem? Thank you in advance.


Solution

  • -(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
            CPoint offset = scrollView.contentOffset;
            int index = offset.x / pageWidth;
            switch (index) {
                case 0:
                    //first ImageView
                    break;
                case 1:
                    //second ImageView
                    break;
                default:
                    break;
            }
        }
    

    Or If you tag your imageViews (starting at 1) you can retrieve them via:

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

    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
        CPoint offset = scrollView.contentOffset;
        int index = offset.x / pageWidth;
        UIImageView *visibileImageView = (id)[scrollView viewWithTag:index+1];
    }
    

    You can use scrollViewDidScroll to detect the position at any point if you use the modulus:

    int index = (offset.x - offset.x % pageWidth)/pageWidth;