@H_301_3@
我实现了一个UITmageView UITableView单元,每个单元通过NSTimer每隔5秒定期刷新一次.每个图像都是从后台线程中的服务器加载的,从后台线程我也通过调用performSelectorOnMainThread更新UI,显示新图像.到现在为止还挺好.
目前,当我不等到当前单元格中加载图像并快速向下滚动到新单元格时,我遇到了问题.然而,该新单元显示先前单元的图像而不是新单元的图像.虽然下一轮NSTimer会正确显示图像,但这可能会让用户感到困惑.
如果我不重用UITableView的单元格,问题就会消失,但考虑到我的应用程序中显示的单元格数量,这不是一个选项.
因此,我能想到的唯一解决方案是,如果我知道用户执行滚动操作,则取消(或终止)将显示旧图像的后台线程.
我想知道这可能不是最好的做法,因此,寻求你的意见.
(我也不能使用SDWebImage,因为我的要求是在从服务器加载的循环中显示一组图像)
// In MyViewController.m - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... NSTimer* timer=[NSTimer scheduledTimerWithTimeInterval:ANIMATION_SCHEDULED_AT_TIME_INTERVAL target:self selector:@selector(updateImageInBackground:) userInfo:cell.imageView repeats:YES]; ... } - (void) updateImageInBackground:(NSTimer*)aTimer { [self performSelectorInBackground:@selector(updateImage:) withObject:[aTimer userInfo]]; } - (void) updateImage:(AnimatedImageView*)animatedImageView { @autoreleasepool { [animatedImageView refresh]; } } // In AnimatedImageView.m -(void)refresh { if(self.currentIndex>=self.urls.count) self.currentIndex=0; ASIHTTPRequest *request=[[ASIHTTPRequest alloc] initWithURL:[self.urls objectAtIndex:self.currentIndex]]; [request startSynchronous]; UIImage *image = [UIImage imageWithData:[request responseData]]; // How do I cancel this operation if I know that a user performs a scrolling action,therefore departing from this cell. [self performSelectorOnMainThread:@selector(performTransition:) withObject:image waitUntilDone:YES]; } -(void)performTransition:(UIImage*)anImage { [UIView transitionWithView:self duration:1.0 options:(UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction) animations:^{ self.image=anImage; currentIndex++; } completion:^(BOOL finished) { }]; }
解决方法
好…
另一种方法是将“图像请求代码”放入AnimatedImageView中,并在每次设置新图像URL时使待处理请求无效
另一种方法是将“图像请求代码”放入AnimatedImageView中,并在每次设置新图像URL时使待处理请求无效
// your controller - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... [cell.imageView setDistantImage:imageURL]; ... }
然后,在你的Cell类中,’setDistantImage’创建一个ASIHttpRequest,并使前一个无效
//your ImageView class @property (...) ASIHttpRequest *distantImageRequest; - (void) setDistantImageUrl:(NSUrl *)imageUrl { //clear prevIoUs request [distantImageRequest clearDelegatesAndCancel]; //set a new request,with the callBack embedded directly in this ImageView class ... } //animation and callBacks methods in this ImageView class too...
@H_301_3@