2

使用 a 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]]
4

1 回答 1

3

首先,我假设您正在运行您在 collectionView:cellForItemAtIndexPath:方法中提供的代码片段,而不是代码中的其他地方。

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

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

您可能希望在访问数组之前验证该addNew数组是否已正确初始化。

于 2013-07-25T08:22:31.247 回答