我有一个UITableView
有两个单元格。一个单元格带有图像,一个单元格没有图像。当没有图像的单元格显示在单元格下方时,图像一切正常(Image 1)。但是当我对列表进行排序并且没有图像的单元格显示在具有图像的单元格上方时,没有图像的单元格显示与另一个单元格(Image 2)相同的图像。
我几天来一直在努力解决这个问题,但我无法找出问题所在。
以下是设置图片的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
Object *myObject = [[Datamodel sharedInstance] objectAtIndex:(int)indexPath.row];
cell.textLabel.text = myObject.name;
if([myObject.imageNames count] != 0 && !myObject.thumbnail)
{
myObject.thumbnail = [[NSString alloc] initWithString:[myObject.imageNames objectAtIndex:0]];
}
if(myObject.thumbnail)
{
NSLog(@"Setting thumbnail");
NSString *pathToImgData= [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents" ]stringByAppendingPathComponent:@"ImgData"];
NSMutableString *imgPath = [[NSMutableString alloc] initWithString:pathToImgData];
[imgPath appendString:@"/"];
[imgPath appendString: myObject.thumbnail];
UIImage* image = [UIImage imageWithContentsOfFile:imgPath];
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(8, 8, 128, cellHeight-16)];
imv.image = image;
[cell addSubview:imv];
}
return cell;
}
关于控制台输出,只有一个对象进入if(myObject.thumbnail)
条件,因此仅针对应该有图像的单元格,图像设置为:
2015-03-01 ***** Cell with image *****
2015-03-01 --> Setting the image
2015-03-01 ***** Cell wihout image *****
2015-03-01 --> NOT setting the image
2015-03-01 ***** Cell without image *****
2015-03-01 --> NOT setting the image
2015-03-01 ***** Cell with image *****
2015-03-01 --> Setting the image
以及对列表进行排序的代码:
-(void)sortList{
NSSortDescriptor *sortObjectName = [NSSortDescriptor sortDescriptorWithKey:@"objectName" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 caseInsensitiveCompare:obj2];
}];
[self.arrayData sortUsingDescriptors:@[sortObjectName]];
}
答案 0 :(得分:2)
您的问题是,您没有设置您不想nil
的单元格图像。
重复使用UITableViewCells
,因此您需要配置您想要或不想要的单元格中的每个值。
只需弄清楚你是否需要呈现图像,如果是这样,如果没有,则设置
UIImageView.image = nil;
答案 1 :(得分:1)
如果没有缩略图,则必须删除图像,因为重复使用了单元格:
if(myObject.thumbnail)
{
NSLog(@"Setting thumbnail");
NSString *pathToImgData= [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents" ]stringByAppendingPathComponent:@"ImgData"];
NSMutableString *imgPath = [[NSMutableString alloc] initWithString:pathToImgData];
[imgPath appendString:@"/"];
[imgPath appendString: myObject.thumbnail];
UIImage* image = [UIImage imageWithContentsOfFile:imgPath];
UIImageView *imv = [cell viewWithTag:1234];
if (!imv) {
imv = [[UIImageView alloc]initWithFrame:CGRectMake(8, 8, 128, cellHeight-16)];
[cell addSubview:imv];
imv.tag = 1234;
}
imv.image = image;
} else {
UIView *imageView = [cell viewWithTag:1234];
if (imageView) {
[imageView removeFromSuperview];
}
}