UICollectionView 在 reloadData 后不调用 didDeselectItemAtIndexPath

UICollectionView does not call didDeselectItemAtIndexPath after reloadData

我试图通过单击一次使 UICollectionViewCell 显示一些信息,并通过再次单击使其内容消失。我首先想到的是使用 didSelectItemAtIndexPath / didDeselectItemAtIndexPath。但是,它不起作用,因为在调用方法 reloadData() 之后,每个 "selected" 单元格的状态都返回到 "unselected",因此永远不会调用 didDeselectItemAtIndexPath 方法。

有什么聪明的方法可以解决这个问题吗?非常感谢您的提前帮助!

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // do something
        self.UICollectionView.reloadData()
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    // do something else
}

非常感谢你们提供的宝贵帮助!我听从了您的建议,添加了一个布尔变量来跟踪单元格是否显示某些内容,并单独使用 didSelectItemAtIndexPath 方法。现在可以使用了!

我相信 BaseZen 的方法也行得通,而且更合法。但是因为不想改太多代码,所以还是选择了比较方便的。但还是谢谢你!

您并没有真正使用 selecting / unselecting 单元格的习语。错误的树。相反,您将需要自定义 UICollectionViewCell 来侦听 Touch Up Inside 事件,并将每次触摸映射到基础数据模型。然后当发生触摸事件时,您可以像这样查找值:

@IBAction func userDidTouchMeLittleCustomCell(sender: UIView) {
    if myCustomDataModel[sender.tag].numTapsSoFar == 0 {
        // do the first UI thing, and then:
        myCustomDataModel[sender.tag].numTapsSoFar++
    }
    else {
        // do the second UI thing, and maybe reset the model? Or whatever applies.
    }
}

现在,您需要确保获取触摸事件的 UIView 配备了正确的 tag,这可以通过 cellForItemAtIndexPath 方法处理。

为了不破坏 select / deselect 习惯用法,您可能希望仅对自定义单元格的 子视图 执行此操作.