我有一个 UICollectionView
,它使用自定义 UICollectionViewCell
类。基本思想是 Collection View 将遍历目录并显示目录中包含的照片(通过 API 调用的结果)。初始 View Controller 显示一个 UICollectionView
,点击单元格会生成一个带有新 UICollectionView
的新 View 。目录内容存储在 NSMutableDictionary
中,目录 ID 是键。
当使用相当短的照片列表(通常少于 30 张)创建新 View / Collection View 时会出现问题。当我旋转设备时, Collection View 尝试重新呈现,应用程序崩溃并显示“index X beyond bounds [0 .. Y]”,其中 X 是大于 Y 的数字(数组的最后一个元素)。
我注意到只有当新显示的 Collection View 的项少于“根” Collection View 时才会发生这种情况。
以下是相关(无论如何)代码的示例:
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
return [[photos objectForKey:api.directoryID] count];
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PhotoCell *photoCell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
photoCell.photo = [[photos objectForKey:api.directoryID] objectAtIndex:indexPath.row];
return photoCell;
}
至少,我想在 cellForItemAtIndexPath
上执行 try/catch,但不知道将 try/catch 放在哪里。也许在自定义 UICollectionView
中?
谢谢!
最佳答案
问题出在这里:
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
return [[photos objectForKey:api.directoryID] count];
}
我假设,您为所有 UICollectionView
实例使用一个 delegate 和 dataSource 对象。
如果是这样,请以这种方式重写您的代码:
- (NSInteger)collectionView:(UICollectionView *)view
numberOfItemsInSection:(NSInteger)section
{
if ( view == _firstCollectionView )
{
return [[photos objectForKey:api.directoryID] count];
}
else if ( view == _secondCollectionView )
{
return ...;
}
}
您还应该以这种方式重写 collectionView:cellForItemAtIndexPath:
方法。
关于ios - cellForItemAtIndexPath 被越界调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14577093/