在UICollectionView中滚动选择错误单元格 - Swift

时间:2014-12-08 17:10:36

标签: ios swift uicollectionview

我有以下UICollectionView,其中Array填充NSManagedObject类型Categories

问题是当选择Cell时,滚动功能无法正常运行。滚动浏览UICollectionView时,其他单元格将被选中并取消选中。奇怪的行为。我认为这是因为滚动后设置不正确的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()
    }
}

1 个答案:

答案 0 :(得分:4)

您不希望调用cellForItemAtIndexPath并在didSelectItemAtIndexPath或didDeselectItemAtIndexPath委托方法中配置单元格。此外,您不应该在cellForItemAtIndexPath方法中调用selectItemAtIndexPath和deselectItemAtIndexPath。

相反,只需在选择/取消选择回调中跟踪并切换所选类别的状态,然后在cellForItemAtIndexPath中设置细胞外观时不要执行任何操作。

正如评论者指出的那样,细胞被重复使用,因此坚持使用委托回调的简单方法,你应该有更好的运气。

如果需要刷新单元格的外观,请在滚动时依赖于调用cellForItemAtIndexPath并使用reloadData和reloadItemsAtIndexPaths集合视图方法(如果需要强制更新)来执行此操作。