我已经在 ScrollView 中完成了延迟加载,如下所示:
-(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];
}
}
}
}
基本上,如果 View 距离屏幕上有+/- 2“页”,则加载 View 。这大大减少了我使用的内存量(而不是一次加载 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];
});
});
}
最佳答案
不久前我遇到了这个问题,我将加载图像从磁盘转移到后台线程。尝试一下,看看是否更快。
请参见此处:loading images from disk in iPhone app is slow
编辑:图像加载滞后也可能是由于 UIImages 处理延迟造成的
请参见此处:Setting image property of UIImageView causes major lag
关于ios - 延迟加载 UIScrollView - 如何使滚动更平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828169/