在reloadData之后,UICollectionView不会调用didDeselectItemAtIndexPath

时间:2015-08-03 04:03:59

标签: ios swift uicollectionview 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的方法也会起作用并且更合法。但由于我不想改变太多的代码,所以我选择了更方便的代码。但是也要感谢!

1 个答案:

答案 0 :(得分:2)

你并没有真正使用选择/取消选择单元格的习语。错了树。相反,您需要自定义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方法处理。

为了不破坏选择/取消选择惯用语,您可能希望仅对自定义单元格的子视图具有此行为。