繁体   English   中英

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

[英]Scrolling in UICollectionView selects wrongs cells - Swift

我有以下UICollectionView由类型为Categories NSManagedObjectArray填充

The problem is that when a Cell is selected scrolling does not function correctly. 滚动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()
    }
}

您不想调用cellForItemAtIndexPath并在didSelectItemAtIndexPathdidDeselectItemAtIndexPath委托方法中配置单元格。
此外,您不应在cellForItemAtIndexPath方法中调用selectItemAtIndexPathdeselectItemAtIndexPath

相反,只需在您的选择/取消选择回调中跟踪和切换所选类别的状态,然后除了在cellForItemAtIndexPath设置单元格的外观之外不要做任何其他cellForItemAtIndexPath

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

如果您需要刷新单元格的外观,请依靠在滚动时调用的cellForItemAtIndexPath并在需要强制更新时使用reloadDatareloadItemsAtIndexPaths集合视图方法来完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM