在UICollectionView滚动select错误单元格 – 斯威夫特

我有以下的UICollectionView它由一个types为NSManagedObjectArray填充

问题是,当一个Cell被选中滚动不能正常工作。 当滚动UICollectionView其他单元格获取选中,并取消select。 奇怪的行为。 我认为这是由于滚动后设置不正确的indexPath? 无论如何,我一直在挣扎几个小时,似乎无法把握。 希望有人能指引我正确的方向!

fetchedCategory被比较到类别来检查它是否已被选中,如果它们是相同的颜色被颠倒。

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("CategorySelectionCollectionCell", forIndexPath: indexPath) as CategoryCollectionViewCell if fetchedCategories[indexPath.row] == category { cell.categoryLabel?.text = fetchedCategories[indexPath.row].name cell.categoryLabel?.textColor = UIColor.whiteColor() cell.backgroundColor = fetchedCategories[indexPath.row].iconColor as? UIColor collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.None) } else { cell.categoryLabel?.text = fetchedCategories[indexPath.row].name cell.categoryLabel?.textColor = fetchedCategories[indexPath.row].iconColor as UIColor collectionView.deselectItemAtIndexPath(indexPath, animated: true) } return cell } func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) { var cell = collectionView.cellForItemAtIndexPath(indexPath) as CategoryCollectionViewCell cell.categoryLabel?.textColor = UIColor.whiteColor() cell.backgroundColor = fetchedCategories[indexPath.row].iconColor as? UIColor category = fetchedCategories[indexPath.row] } func collectionView(collectionView: UICollectionView!, didDeselectItemAtIndexPath indexPath: NSIndexPath!) { if var cell = collectionView.cellForItemAtIndexPath(indexPath) as? CategoryCollectionViewCell { cell.categoryLabel?.text = fetchedCategories[indexPath.row].name cell.categoryLabel?.textColor = fetchedCategories[indexPath.row].iconColor as UIColor cell.backgroundColor = UIColor.whiteColor() } } 

您不想调用cellForItemAtIndexPath并在didSelectItemAtIndexPath或didDeselectItemAtIndexPath委托方法中configuration单元格。 另外,您不应该在cellForItemAtIndexPath方法内调用selectItemAtIndexPath和deselectItemAtIndexPath。

相反,只要在select / deselectcallback中跟踪并切换所选类别的状态,然后不要做任何其他设置cellForItemAtIndexPath中的单元格外观。

正如评论者所指出的那样,细胞被重复使用,所以坚持使用委托callback的简单方式,你应该有更好的运气。

如果需要刷新单元格的外观,可以通过在滚动时调用cellForItemAtIndexPath并在需要强制更新时使用reloadData和reloadItemsAtIndexPaths集合视图方法来实现。