为什么UICollectionView.cellForItemAtIndexPath始终调用UICollectionViewDatasource.cellForItemAtIndexPath?

时间:2014-06-04 17:42:00

标签: ios uicollectionview

场景:我想检查具有indexPath的特定可见UICollectionViewCells的选定状态,我在UICollectionView引用上调用了cellForItemAtIndexPath。

问题:调用UICollectionView.cellForItemAtIndexPath始终调用UICollectionViewDatasource.cellForItemAtIndexPath,它返回一个没有选择状态的新单元格。

问题:为什么UICollectionView.cellForItemAtIndexPath始终调用UICollectionViewDatasource.cellForItemAtIndexPath?

Apple文档说返回值是“相应索引路径上的单元格对象,如果单元格不可见或者indexPath超出范围,则为nil。”

我是否遗漏了某些内容,或者我的数据源中的cellForItemAtIndexPath实现不正确?

- (UICollectionViewCell*) collectionView: collView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

SudoCell *cell = [collView dequeueReusableCellWithReuseIdentifier:CELL_ID forIndexPath:indexPath];
[cell setValuesWithSection:indexPath.section item:indexPath.item modelObject:_model];
cell.backgroundColor =  [UIColor whiteColor];

return cell;

}

作为当前的解决方法,我正在设置将section和item值存储为单元格的实例值。循环遍历所有可见单元格以查找具有section和item值的匹配单元格并检查可见状态。当细胞数量很大时,这就变得乏味了。

请建议。

1 个答案:

答案 0 :(得分:0)

您误解了协议和代理的工作方式。 cellForItemAtIndexPath:是UICollectionView和UITableView在其数据源上调用的委托方法,用于填充Collection或Table View。

因此,假设您有一个CollectionView,并为其提供了数据源。在运行应用程序的某个时刻,CollectionView将调用数据源numberOfSectionsInCollectionView上的方法:以获取CollectionView需要多少部分

然后它调用collectionView:numberOfItemsInSection以获取集合的每个部分的项目。为集合视图中定义的每个单独的部分调用此方法。

最后,它调用collectionView:cellForItemAtIndexPath:以获取集合中每个项目的Cells。为集合视图中定义的每个单独的项调用此方法。这是您可以以编程方式配置单元格以显示所需信息的位置,例如,如果您希望为集合提供附加了图像的单元格,则可以在此处执行此操作。

https://developer.apple.com/library/ios/documentation/uikit/reference/UICollectionViewDataSource_protocol/Reference/Reference.html

这些都是数据源方法,全权负责为Collection View提供数据。如果要响应用户交互,则需要使用UICollectionViewDelegate协议并实现方法

的CollectionView:didSelectItemAtIndexPath:

的CollectionView:didDeselectItemAtIndexPath:

正如签名所暗示的那样,这些方法被调用以响应对集合执行的操作,以及描述执行操作的单元格的节和项目编号的IndexPath。

https://developer.apple.com/library/ios/documentation/uikit/reference/UICollectionViewDelegate_protocol/Reference/Reference.html

上面的UICollectionDelegate协议引用可用于响应该视图中发生的不同事件

但如果您对协议和代表没有基本的了解,那么上述信息都不会对您有任何用处。在继续

之前,我建议先花时间加强理解
相关问题