a view that iterates a list with images and animations in swift

You can use UICollectionView to show a list of images with animation. Here are the steps:

  1. import UIKit and create a UICollectionView in your UIViewController.
main.swift
class YourViewController: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!
}
104 chars
4 lines
  1. Set the UICollectionViewDataSource and UICollectionViewDelegate of your collection view. You can do this in viewDidLoad().
main.swift
override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self
    collectionView.delegate = self
}
128 chars
6 lines
  1. Implement the UICollectionViewDataSource methods to return the number of items and the cell at an index path.
main.swift
extension YourViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return yourImages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellIdentifier", for: indexPath) as! YourCollectionViewCell
        
        cell.imageView.image = yourImages[indexPath.item]
        
        return cell
    }
}
574 chars
14 lines
  1. Create a custom UICollectionViewCell with an UIImageView and any other views you want to show.
main.swift
class YourCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    // add any other views you want to show
}
146 chars
5 lines
  1. Implement the animation in collectionView(_:willDisplay:forItemAt:) method of UICollectionViewDelegate. You can use UIView.animate(withDuration:) to animate the views in the cell.
main.swift
extension YourViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let yourCell = cell as! YourCollectionViewCell
        
        yourCell.imageView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
        UIView.animate(withDuration: 0.5) {
            yourCell.imageView.transform = CGAffineTransform.identity
            // add animation for any other views you added
        }
    }
}
524 chars
12 lines
  1. Set the layout of your collection view as you want. You can use UICollectionViewFlowLayout to create a simple layout.
main.swift
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: YourItemWidth, height: YourItemHeight)
layout.sectionInset = UIEdgeInsets(top: YourTopInset, left: YourLeftInset, bottom: YourBottomInset, right: YourRightInset)
collectionView.collectionViewLayout = layout
281 chars
5 lines

That's it! Now your collection view will show a list of images with animation.

gistlibby LogSnag