Ios 每次滚动tableview时,单元格中的图像都会发生变化
在下面的代码中,每当我滚动tableview时,每个单元格中的图像都会发生变化,这是不应该发生的。请帮忙。提前谢谢Ios 每次滚动tableview时,单元格中的图像都会发生变化,ios,objective-c,uitableview,Ios,Objective C,Uitableview,在下面的代码中,每当我滚动tableview时,每个单元格中的图像都会发生变化,这是不应该发生的。请帮忙。提前谢谢 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UserDetails *userDetails = [arrUserDetails objectAtIndex:indexPath.row]; static NSString
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UserDetails *userDetails = [arrUserDetails objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"CustomCell";
__weak TableViewCell *cell = (TableViewCell *)[_tableViewUsername dequeueReusableCellWithIdentifier:CellIdentifier];
cell.tag = indexPath.row;
cell.userName.text = userDetails.userName;
[self.operationQueue addOperationWithBlock: ^ {
NSURL *aURL = [NSURL URLWithString:userDetails.userImageURL];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:aURL options:nil error:&error];
UIImage *image = nil;
if (cell.tag == indexPath.row)
{
image = [UIImage imageWithData:data];
[[NSOperationQueue mainQueue] addOperationWithBlock: ^ {
cell.customImageView.image = image;
cell.customImageView.contentMode = UIViewContentModeScaleToFill;
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}];
}
}];
在从url加载图像之前,请为图像添加默认占位符,因为单元格将被重新使用,因此将使用上一个图像您可以使用SDWebImage.framework加载图像
[cell.customImageView sd_setImageWithURL:[NSURL URLWithString:userDetails.userImageURL] placeholderImage:nil options:SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image) {
[cell.customImageView setImage:image];
}
}];
您可以使用Afnetworking类来实现此目的 只需导入#导入“UIImageView+AFNetworking.h” 并使用这条线:- [cell.imgProfile setImageWithURL:imgurl占位符图像:[UIImage ImageName:@”“]强>
Imgurl是您从response中获得的图像Url了解更多有关
UITableView
工作原理的信息。单元一直在排队和重用。这就是为什么您会看到图像指向您认为错误的单元格,但对于iOS,它们是正确的,因为cell.tag==indexPath.row
。您需要比标记更可靠的引用。请使用自定义单元格并定义其属性,如名称标签和图像视图。这将保留对哪个单元格的可靠引用,并解决由当前代码引起的问题,即每次调用委托方法时都创建UIElements。@muku是正确的-您没有设置默认图像或至少在加载新图像时清除旧图像。还可以考虑使用类似SDWEBIVE的图像来提供更好的性能,然后将图像设置为CytoCuffIVIEVIEW。
[cell.customImageView sd_setImageWithURL:[NSURL URLWithString:userDetails.userImageURL] placeholderImage:nil options:SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image) {
[cell.customImageView setImage:image];
}
}];