2
我已經完成延遲加載:延遲加載的UIScrollView - 如何在一個滾動視圖這樣滾動平滑
-(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多個ItemViews),這很好。但是,所有加載/卸載都會使滾動變得有點波動,特別是在較慢的設備上。下面是實際發生的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];
});
});
}
很好的建議:圖像加載滯後也可以通過UIImages
看到這裏的處理延遲造成的。不幸的是,舊設備仍然存在滯後性。你可以看看我的編輯,在「嘗試異步」下,看看我是否做錯了什麼? – soleil
也許在較慢的設備上,在屏幕上繪製它會使其滯後。我解決了使用縮略圖(也就是質量較低的圖像)來解決較慢設備的問題。您正在正確加載後臺線程中的圖像。你的圖像真的是高清?他們需要成爲HD嗎? – yuf
你好,請仔細閱讀這個問題:http://stackoverflow.com/questions/10790183/setting-image-property-of-uiimageview-causes-major-lag這可能是你的問題 – yuf