简体   繁体   中英

UICollectionView does not call didDeselectItemAtIndexPath after reloadData

I'm trying to make the UICollectionViewCell display some information by clicking it once, and make its content disappear by click it again. The first thing comes up to my mind is to use didSelectItemAtIndexPath / didDeselectItemAtIndexPath. However, it does not work because after the method reloadData() is called, every "selected" cell's status goes back to "unselected" so that the didDeselectItemAtIndexPath method is never called.

Is there any smart way to get around this problem? Many thanks for your kind help in advance!

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

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

Thank you so much for your invaluable help guys! I followed your advice by adding a boolean variable to keep track of whether a cell is displaying something or not and use the didSelectItemAtIndexPath method alone. It now works!

I believe BaseZen's approach would also work and is more legitimate. But since I don't want to change too many codes, so I chose the more convenient one. But thanks all the same!

You're not really using the idiom of selecting / unselecting cells. Wrong tree. Instead you'll need your custom UICollectionViewCell to listen to Touch Up Inside events, and map each touch to an underlying data model. Then when a touch up event occurs, you look up the value like so:

@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.
    }
}

Now, you'll need to be sure that the UIView getting the touch event is outfitted with the proper tag , which can be handled by the cellForItemAtIndexPath method.

In order not to break the select / deselect idiom, you may want to have this behavior for only a subview of your custom cell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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