Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/108.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 根据单元格索引XPath,.reloadData()中的幕后工作是什么?_Ios_Swift_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

Ios 根据单元格索引XPath,.reloadData()中的幕后工作是什么?

Ios 根据单元格索引XPath,.reloadData()中的幕后工作是什么?,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我使用集合视图,每次选择单元格时,我都会将单元格背景颜色更改为红色。很简单: override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath)! as! CustomCell cell.backgroundColor = .red }

我使用集合视图,每次选择单元格时,我都会将单元格背景颜色更改为红色。很简单:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)! as! CustomCell
    cell.backgroundColor = .red
}
这绝对行得通。当我从左向右选择前3个单元格时,背景颜色的变化与我预期的完全一致:

但是,如果在选择单元格后重新加载collectionView,则选择顺序开始异常。当我按从左到右的相同顺序选择相同的前3个单元格时,会选择不同的单元格:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)! as! CustomCell
    cell.backgroundColor = .red
    collectionView.reloadData()
}

苹果的文档很神秘

他们说“这会导致集合视图丢弃任何当前可见的项(包括占位符),并根据数据源对象的当前状态重新创建项。”但这让我认为,在调用reloadData()时,collectionViewCells将返回灰色,而不是跳转IndExpath


有人能解释一下reloadData()中发生了什么,使得索引路径排序中的单元格选择如此奇怪吗?

首先,您需要使用出列单元格

let cell=collectionView.dequeueReusableCell(使用reuseidentifier:“CustomCell”,for:indexath)作为!自定义单元格

在手机里你可以使用

-(void)prepareForReuse {
  // Set default implementation 

}

阅读
UICollectionViewDataSource cellForItemAt
UICollectionView dequeueReusableCell
的文档。您还应该阅读.Hi@rmaddy在阅读了您建议的文档和提供的链接后,我逐渐了解到重新排序与集合视图布局有关。但是,我无法找到重新加载数据对布局的确切影响。有进一步阅读的建议吗?没有。实际上,它与布局无关,甚至与重新加载数据无关。只需滚动您的集合视图(如果您有足够的项目)就会导致您的问题。这是由单元格重用引起的。@rmaddy,因此dequeueResuableCell返回一个有效的可重用视图,就像集合视图单元格一样。文档声明“集合视图将它们放在重用队列中,而不是在它们滚动到可见边界之外时将其删除。”但在这种情况下,没有任何单元格超出边界。这不意味着什么都不能重复使用吗?