Ios UITableView在滚动中更改了图像
每次我滚动TableView时,我的图像都会被弄乱,主要是第一行。我真的不知道该怎么办 代码如下:Ios UITableView在滚动中更改了图像,ios,objective-c,uitableview,uiimage,Ios,Objective C,Uitableview,Uiimage,每次我滚动TableView时,我的图像都会被弄乱,主要是第一行。我真的不知道该怎么办 代码如下: - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; BarCell *cell = [tableView dequeueReusable
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
BarCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
[cell.activityFotoBar startAnimating];
cell.activityFotoBar.hidesWhenStopped = YES;
if(!cell){
cell = [[BarCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSMutableDictionary *infoBar = [self.bares objectAtIndex:indexPath.row];
NSString *nomeImagem = [infoBar objectForKey:@"foto"];
NSURL *url = [NSURL URLWithString:nomeImagem];
NSURLRequest *requestImagem = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:requestImagem queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(connectionError == nil){
cell.imageViewImagemBar.image = [UIImage imageWithData:data];
[cell.activityFotoBar stopAnimating];
}
}];
cell.labelNomeBar.text = [infoBar objectForKey:@"nome"];
cell.labelEnderecoBar.text = [infoBar objectForKey:@"endereco"];
cell.labelAvaliacaoBar.text = [NSString stringWithFormat:@"Votos: %@", [infoBar objectForKey:@"votos"]];
return cell;
}
提前谢谢 发生此问题的原因是,异步映像请求在单元格从屏幕上滚动并重新使用后完成。下载完全“无序”,造成视觉混乱。本质上,一些通过滚动重新使用的单元格仍然是“热”的,因为它们的图像加载正在进行中。重用这样的单元会在旧图像下载和新图像下载之间产生竞争
您应该更改用于加载图像的策略:而不是发送请求和“忘记”,请考虑使用<代码>连接连接请求:委托:方法,将连接存储在单元格中,并在“代码>准备好重用/<代码>方法”时调用“代码>取消/代码>。这样,重复使用的单元格将是“冷的”。
您可以使用SDWebcache库。它包含一个UIImageView类别,可以从URL加载图像。我发现它与TableView配合得很好,代码应该“几乎”可以工作。您只需解决一个问题即可使其正常工作(尽管不是最佳情况): 异步请求sendAsynchronousRequest:queue:completionHandler:
完成后,将调用完成处理程序。然后,需要从表视图中再次检索单元格,在请求启动时指定indexPath
您只需要在块内捕获indexPath,以获得在块完成之前保持有效的引用
UITableView
检索单元格的方法是
-(UITableViewCell*)cellForRowAtIndexPath:(NSIndexPath*)indexPath
如果返回值(单元格)为nil
,则索引路径indexPath处的单元格不可见
因此,完成块将如下所示:
if (error == nil && ... ) {
BarCell* cell = [self.tableView cellForRowAtIndexPath:indexPath]
if (cell) {
cell.imageViewImagemBar.image = [UIImage imageWithData:data];
[cell.activityFotoBar stopAnimating];
}
}
它还可以安全地处理单元格为零的情况
注意:虽然这种方法“有效”,但它仍然是一种幼稚的方法。一种更复杂的方法是缓存(解码)的图像,并可能有一些“前瞻和急切驱逐策略”,以获得更好的用户体验和更低的内存足迹
请注意,
imageWithData:
可能仍然很昂贵,因为在渲染图像之前,可能需要对图像进行解码、解压缩和调整大小。基本上,这可以在屏幕外的上下文中提前执行。你说的混乱是什么意思?假设你不应该在CellForRow中加载图像,第一行的图像被第三行或第四行替换,依此类推。这是随机的。你介意我请你给我举个例子吗?我是新来的。谢谢。@Fernandosaares在这方面我不可能比苹果做得更好-看看他们的样品:。