我已经在这样的滚动视图中完成了延迟加载:
-(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];
});
});
}