Search code examples
iosswiftanimationuicollectionviewuiimageview

Swift - present/dismiss ViewController with UIImage animation


I would like to have an animation when pushing/dismissing my ViewController.

The best way to show you what I mean is to look at the N26: Animation

In my case I have a CollectionView where the user can click on a cell to get to the next ViewController which I handle with a tapCallback:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // if indexPath.item is less than data count, return a "Content" cell
    if indexPath.item < dataSourceArray.count {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) as! ContentCell
        // set cell label
        cell.cellLabel.text = dataSourceArray[indexPath.item].name
        // set cell image
        cell.wishlistImage.image = dataSourceArray[indexPath.item].image
        if cell.wishlistImage.image == images[2] || cell.wishlistImage.image == images[3] {
            cell.priceLabel.textColor = .gray
            cell.priceEuroLabel.textColor = .gray
            cell.wishCounterLabel.textColor = .gray
            cell.wünscheLabel.textColor = .gray
        }
        // set background color
        cell.imageView.backgroundColor = dataSourceArray[indexPath.item].color
        cell.wishCounterView.backgroundColor = dataSourceArray[indexPath.item].color
        cell.priceView.backgroundColor = dataSourceArray[indexPath.item].color


        cell.customWishlistTapCallback = {

            // track selected index
            self.currentWishListIDX = indexPath.item

            let vc = self.storyboard?.instantiateViewController(withIdentifier: "WishlistVC") as! WishlistViewController

            vc.wishList = self.dataSourceArray[self.currentWishListIDX]

            vc.theTableView.tableView.reloadData()
            self.present(vc, animated: true, completion: nil)

        }

        return cell
    }

To dismiss the ViewController the user simply has to tap a button:

@objc private func dismissView(){
    self.dismiss(animated: true, completion: nil)
}

This is a screenshot of my CollectionView and the ViewController I present/dismiss:

enter image description here enter image description here

Like I said I would like to have the exact same animation as in the video (also be able to "drag-dismiss" the ViewController but that is probably another question?).

If you anything is unclear feel free to ask.

I tried searching for that but I couldn't really find anything so I am grateful for any help :)


Solution

  • There is a really good library that does this functionality, it’s called Hero.

    If you want to make your own implementation you will need to use your own UIViewControllerTransitioningDelegate