我已经在这样的 ScrollView 中完成了延迟加载:
-(void)scrollViewDidScrollUIScrollView *)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)layoutWithDataItem*)_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 actionselector(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)layoutWithDataItem*)_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 actionselector(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/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |