iosswiftuicollectionviewtvosuicollectionviewflowlayout

How to move selected row to the top of UICollectionView


I have a UICollectionView of UICollectionView, so each row has 1 cell with a UICollectionView inside.

I want that the selected row always move to the top of the my CollectionView, currently the selected row is centered inside the CollectionView.

Does someone know how to achieve this ? I tried to play with a custom UICollectionViewFlowLayout but without success...

What I have below (grey box is my CollectionView): What I have below (grey box is my CollectionView)

What I would like to have (grey box is my CollectionView): What I would like to have (grey box is my CollectionView)]2


Solution

  • You can scroll to the selected item using This:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         self.collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
    }
    
    

    The some of the last items will not goes to top because it won't have more space to move top so for fix that you have to calculate & set tableview bottom inset.