【问题标题】:UICollectionView - multiple, different cellsUICollectionView - 多个不同的单元格
【发布时间】:2024-01-17 03:27:01
【问题描述】:

使用UICollectionView,我正在尝试添加另一个UICollectionViewCell。第一个代码显示了第一个 Cell,它运行良好。当我尝试添加另一个 UICollectionViewCell 时会出现问题。

static NSString *identifier = @"Cell"; // Default Cells

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *illustrationImage = (UIImageView *)[cell viewWithTag:100];
illustrationImage.image = [UIImage imageNamed:[stackImage objectAtIndex:indexPath.row]];

UILabel *stackLabel = (UILabel *)[cell viewWithTag:12];
[stackLabel setText:[stackTitle objectAtIndex:indexPath.row]];

在这里,我想向我的UICollectionView 添加一个具有不同内容的全新单元格。每当我运行这段代码时,整个事情都会拒绝启动:

static NSString *newIdentifier = @"AddNewCell"; 

UICollectionViewCell *newCell = [collectionView dequeueReusableCellWithReuseIdentifier:newIdentifier forIndexPath:indexPath];

UIImageView *addNewImage = (UIImageView *)[newCell viewWithTag:120];
addNewImage.image = [UIImage imageNamed:[addNew objectAtIndex:indexPath.row]]; // This line makes the app crash

return cell;
return newCell;

错误信息

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]”

我怀疑这与indexPath.row 有关。 如果我将以下代码中的indexPath.row 部分替换为“0”,则它不会崩溃,但不会在UICollectionView 中可见:

[addNew objectAtIndex:indexPath.row]]

【问题讨论】:

    标签: ios ios6 uicollectionview uicollectionviewcell


    【解决方案1】:

    首先,我假设您正在运行您在 collectionView:cellForItemAtIndexPath: 方法,而不是代码中的其他位置。

    此外,您不能在上述方法内同时创建(也不能返回!!)两个单元格。您应该根据作为参数接收的索引路径来决定出列、实例化和返回哪个单元格。

    现在,关于您收到的“索引超出范围”错误:您正在尝试访问名为 addNew 的数组元素,该元素实际上并不存在于数组中您想访问它的那一刻。在您的情况下,您尝试访问数组的第二个元素(索引1)并且数组只有一个元素(索引0)。

    您可能想要验证addNew 数组在您访问它之前 是否已正确初始化。

    【讨论】: