Search code examples
swiftuicollectionviewuicollectionviewcelluicollectionviewflowlayout

How to keep collection view cell selected when presenting and dismissing modal view controller?


I have a UICollectionViewController that is also acts as UICollectionViewDelegateFlowLayout to size cells. One cell selection modally presents some custom controls and then returns when completed, but the selected cell is no longer selected when it reappears.

I see delegate method for collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) being called, but not collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath). I also see the layout being asked for the preferred cell size, so I’m thinking they are being redrawn, but the cells already exist.

I can solve the problem by calling relaodData(), and the cell knows it is selected, and is redrawn accordingly, but that seems like a costly and wrong solution. Any suggestions about what I am missing? Thanks.


Solution

  • Figured it out.

    UICollectionViewController has property clearsSelectionOnViewWillAppear that is automatically set to true.

    All I had to do was set it to false.