首页 > 开发 > iOS > 正文

UITableVIew 从服务器加载的图片乱了

2017-09-08 14:04:08  来源:网友分享

我有一个TableView的界面,是一个列表页,只有一个Section,每一个Cell里都有一张图片是从服务器异步加载的。
我用ASIHttpRequest去加载图片,在每个Request里已经通过UserInfo带上了这个Cell的NSIndexPath.row,然后回调的时候,就按照这个NSIndexPath去更新Cell的默认占位图片。
但是,我发现刷两下以后,Cell里的图片又乱掉了。。。
貌似我NSIndexPath.row没用一样的。。。有没有人也遇到过一样的问题啊。。。

完整代码太复杂,把涉及到网络的代码贴一下

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{// ...    [self loadImageWithURL:[self.dataSource objectAtIndex:indexPath.row]                     index:indexPath.row]; // 这是我自己定义的一个方法// ...}- (void)loadImageWithURL:(NSString *)aURL index:(NSInteger)anIndex {    ASIHTTPRequest *asiRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:aURL]];    asiRequest.delegate = self;    asiRequest.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:                            [NSString stringWithFormat:@"%d", anIndex],                            @"index",                            nil];    asiRequest.requestMethod = @"GET";    [asiRequest startAsynchronous];}- (void)requestFinished:(ASIHTTPRequest*)request {    NSInteger index = [[request.userInfo objectForKey:@"index"] intValue];    UITableViewCell *cell = [tableView cellForRowAtIndexPath:                                [NSIndexPath indexPathForRow:index                                                   inSection:0]];    cell.imageView.image = [UIImage imageWithData:request.responseData];}

解决方案

刷新TableView后,每个Cell所对应的图片URL是否有变化?

要知道图片的网络请求可能在刷新前发出,在刷新后才收到回应。可能这个原因造成了图片的混乱。

因此,还是建议将每个图片请求对应到每个具体的ImageView上,即将请求放到ImageView里,并保证在ImageView滑出屏幕时(Cell会收到prepareForReuse消息)取消相应的请求。
具体的实现可以参考SDWebImage (https://github.com/rs/SDWebImage) 或 EGOImageLoading (https://github.com/enormego/EGOImageL...