Search code examples
swiftuicollectionviewuicollectionviewcellviewcontroller

Hero ViewController animation with collectionView - swift


I'm trying to present a view controller whenever I tap on a collection view cellwith the zoom effect.

As far as I know Hero framework works using HeroID's, you set the same id in the fromView and in the toView and the frameworks does the hard work for you.

I have set It up this way:

in viewcontroller1 :

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
    cell.heroID = "profheroid"
    let viewcontroller2 = ViewController2()
    viewcontroller2.configureController(with: arrayOfModels[indexPath.item])
    viewcontroller2.heroModalAnimationType = .zoom
    viewcontroller2.modalPresentationStyle = .fullScreen
    self.navigationController?.present(viewcontroller2, animated: true, completion: nil)
}

and in viewcontroller2:

override func viewDidLoad() {
    super.viewDidLoad()
    view.heroID = "profheroid"
}

The problem happens whenever I tap on a collectionviewCell the presentation happens correctly but I see so many cells being presented at the same time. I think this happens because cell.heroID = "profheroid" is applied to more cells at the same time.

How can I make sure that when the cell is presented the heroID's are only in the cell tapped and in the viewcontroller's view??


Solution

  • I think you must clear this heroID when cell is reused and after VC is presented.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        cell.heroID = nil // or empty
    }