2

我已经在这样的滚动视图中完成了延迟加载:

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

    int currentPage = (1 + myScrollView.contentOffset.x / kXItemSpacingIphone);
    for (ItemView* itemView in [self.itemRow subviews]){
        if (itemView.tag >= currentPage-2 && itemView.tag <= currentPage+2)
        {
            //keep it visible
            if (!itemView.isLoaded) {
                [itemView layoutWithData:[self.items objectAtIndex:itemView.tag-1]];
            }
        }
        else
        {
            //hide it
            if (itemView.isLoaded) {
                [itemView unloadData];
            }

        }
    }
}

如果它在屏幕上的+/- 2“页面”基本上加载视图。这大大减少了我正在使用的内存量(而不是一次加载 20 多个 ItemView),这很好。但是,所有加载/卸载确实使滚动有点不稳定,尤其是在速度较慢的设备上。这是 ItemView 加载时实际发生的情况:

- (void)layoutWithData:(Item*)_data {
    self.data = _data;

//grab the image from the bundle
    UIImage *img;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:_data.image ofType:@"jpg"];
        if(filePath.length > 0 && filePath != (id)[NSNull null]) {
            img = [UIImage imageWithContentsOfFile:filePath];
        }

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:img forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(tapDetected:) forControlEvents:UIControlEventTouchUpInside];
    btn.frame = CGRectMake(0, 0, kItemPosterWidthIphone, kItemPosterHeightIphone);
    [self addSubview:btn];

    self.isLoaded = YES;

}

和 ItemView 卸载:

- (void)unloadData{
    for(UIView *subview in [self subviews]) {
        [subview removeFromSuperview];
    }
    self.data = nil;
    self.isLoaded = NO;
}

同样,我能做些什么来使加载/卸载更快,从而使 UIScrollView 更流畅?


尝试异步:

- (void)layoutWithData:(Item*)_data {
    self.data = _data;
    self.isLoaded = YES;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        UIImage *img;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:_data.image ofType:@"jpg"];
            if(filePath.length > 0 && filePath != (id)[NSNull null]) {
                img = [UIImage imageWithContentsOfFile:filePath];
            }

        dispatch_async(dispatch_get_main_queue(), ^{
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setImage:img forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(tapDetected:) forControlEvents:UIControlEventTouchUpInside];
            btn.frame = CGRectMake(0, 0, kItemPosterWidthIphone, kItemPosterHeightIphone);
            self.imageView = btn;
            [self addSubview:btn];


        });

    });
}
4

1 回答 1

4

不久前我遇到了这个问题,我将加载图像从磁盘移动到后台线程。试试看它是否更快。

见这里:在 iPhone 应用程序中从磁盘加载图像很慢

编辑:图像加载滞后也可能是由 UIImages 的延迟处理引起的

请参阅此处:设置 UIImageView 的图像属性会导致严重滞后

于 2012-10-10T21:29:27.097 回答