【问题标题】:Custom Collection View Cells Showing the wrong image自定义集合视图单元格显示错误的图像
【发布时间】:2013-10-14 10:09:34
【问题描述】:

我的捆绑资源中有大约 80 张图片。作为我的类别类的一部分,我有一个名为 Image Name 的属性,它包含我需要加载到图像视图中的图像的名称。我使用 [UIImage imageNamed:Category.imageName]。这会在自定义表格单元格中加载正确的图像,但不会在集合视图单元格中加载。

表格视图 - 索引路径处的行的单元格

NSLog(@"Index = %d",indexPath.row);
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
if(cell == nil){
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"CustomTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}
Category *current = [self.editCategories objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[[cell itemTitle]setText:current.title];
cell.backgroundColor = current.categoryColor;
cell.itemImage.image = [UIImage imageNamed:current.imageName];

return cell;

集合视图 - 索引路径处的行的单元格......

NSArray *catagoriesPulled = [[CategoryStore categoryStore]allCatagories];
Category *categoryRequested = [catagoriesPulled objectAtIndex:[indexPath row]];
CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCollectionViewCell" forIndexPath:indexPath];
[cell setController:self];
cell.categoryImageView.image = nil;
cell.categoryTitle.numberOfLines = 1;
cell.categoryTitle.adjustsFontSizeToFitWidth = YES;
[[cell categoryTitle]setText:categoryRequested.title];
cell.categoryImageView.image = [UIImage imageNamed:categoryRequested.imageName];
NSLog(@"%@,%@",categoryRequested.title, categoryRequested.imageName);
cell.backgroundColor = categoryRequested.categoryColor;
return cell;

当我在模拟器上运行应用程序时,它可以完美运行,但在实际设备上,集合视图单元格的图像视图会从包含的 80 个随机图像中加载,但表格视图会加载正确的图像。

任何帮助都会很有用。谢谢。

【问题讨论】:

    标签: ios objective-c uicollectionview


    【解决方案1】:

    当您这样做时,您是否有正确的图像名称: NSLog(@"%@,%@",categoryRequested.title, categoryRequested.imageName); ?

    您可能想用[cell setController:] 检查您的CustomCollectionView 中是否没有保留周期。这通常会导致一些奇怪的事情发生(尤其是在内存较低的设备上,我发现)。您可能会保留这些单元格及其子视图的额外实例,这可能是导致出现错误图像的原因。

    【讨论】:

    • 我循环浏览了日志,正确的图像名称与每个类别相关联,并且我没有在任何地方使用保留语句。无论如何,非常感谢。
    • 您实际上不必使用[myObject retain] 来进行保留周期。如果您删除 [cell setController:self],这种情况还会发生吗?
    • 我的意思是,我认为这里有一个“A 类保留 B 类保留 A 类”的事情,其中​​ self 保留每个 tableViewCell,每个 tableViewCell 保留自己。 here is a good article explaining this.
    • 我会调查的。非常感谢!
    【解决方案2】:

    当您创建自定义单元格时,您可能已经更改了 imageview 的默认名称...没关系,但请确保将其链接到 xib 文件的 outlets 部分。 (单击您的 xib 文件,然后单击自定义单元格,然后查看以确保其链接)

    编辑: 根据您的评论,听起来这几乎是一个问题,您必须对应用程序进行清理(产品->清理),同时从手机或模拟器中删除应用程序。然后重建并显示新图像。当您将图像更改为另一个图像但保持相同的文件名时,可能会发生这种情况。该文件有时可以缓存在设备上。

    【讨论】:

    • 是的,我确定我添加了它。我尝试使用不同的方式访问图像、图像命名或 nsbundle 主包,但它仍然显示不同的图片