如何使用大量图像优化UIScrollView

时间:2012-04-19 04:20:14

标签: ios uiscrollview

我一次在UIScrollView中加载所有图像,我知道这是不好的方式,那么有没有更好的方法来优化它?

4 个答案:

答案 0 :(得分:3)

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int currentPage = (scrollView.contentOffset.x / scrollView.frame.size.width);

    // display the image and maybe +/-1 for a smoother scrolling
    // but be sure to check if the image already exists, you can
    // do this very easily using tags
    if ([scrollView viewWithTag:(currentPage + 1)]) {
        return;
    } else {
        // view is missing, create it and set its tag to currentPage+1
        UIImageView *iv = [[UIImageView alloc] initWithFrame:
            CGRectMake((currentPage + 1) * scrollView.frame.size.width,
                       0,
                       scrollView.frame.size.width,
                       scrollView.frame.size.height)];
        iv.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg",
                                                                  currentPage + 1]];
        iv.tag = currentPage + 1;
        [sv addSubview:iv];
    }

    /**
     * using your paging numbers as tag, you can also clean the UIScrollView
     * from no longer needed views to get your memory back
     * remove all image views except -1 and +1 of the currently drawn page
     */
    for (int i = 0; i < 50; i++) {
        if ((i < (currentPage - 1) || i > (currentPage + 1)) &&
            [scrollView viewWithTag:(i + 1)]) {
            [[scrollView viewWithTag:(i + 1)] removeFromSuperview];
        }
    }
}

答案 1 :(得分:1)

您可以使用this教程来帮助您。虽然我也建议用户1212112说什么,并观看WWDC 2011 Session 104 - Advanced Scroll View Techniques

答案 2 :(得分:0)

VSScrollview查看VSScrollview。它重用了你传递给它的观点。它的使用很简单,就像使用UITableview一样。实施以下数据方法

-(VSScrollViewCell *)vsscrollView:(VSScrollView *)scrollView viewAtPosition:(int)position;
// implement this to tell VSScrollview the view at position "position" . This view is VSScrollviewCell or subclass of VSScrollviewCell.

-(NSUInteger)numberOfViewInvsscrollview:(VSScrollView *)scrollview;

// implement this to tell VSScrollview about number of views you want in VSSCrollview.

还有其他可选的数据源和委托方法,您可以通过它们自定义VSScrollview的行为。每个视图的scrollview可以有不同的宽度,高度,间距甚至内容大小。

答案 3 :(得分:0)

我知道它是旧线程,但是任何寻求解决方案的人都可以看一下:https://github.com/sumofighter666/ReusableScrollView