How do I animate my collection view cells smaller when editing?

advertisements

So I have a collection view which lays out cells 2 per row. When I go into editing mode I would like for the cells to reduce in size all around. I tried adding padding to them to get the desired effect which works but I need them to animate in! How could I accomplish this. Please see my code bellow:

Initial set up when view loads:

 override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = editButtonItem
    navigationController?.isToolbarHidden = true

    // Does not allow to move items around innitialy
    installsStandardGestureForInteractiveMovement = false

    // set collectionView item size
    //let width = collectionView!.frame.width/2
    let layout = collectionViewLayout as! UICollectionViewFlowLayout
    let itemsPerRow: CGFloat = 2.0
    let paddingSpace: CGFloat = 2.0 * itemsPerRow
    let availableWidth = view.frame.width - paddingSpace
    let widthPerItem = availableWidth / itemsPerRow
    layout.minimumLineSpacing = 4.0
    layout.itemSize = CGSize(width: widthPerItem, height: widthPerItem)

}

Then this is what gets called when "edit" is tapped

func reduceCellSize() {

    if isEditing {
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout

        let itemsPerRow: CGFloat = 2.0
        let paddingSpace: CGFloat = 8.0 * itemsPerRow
        let availableWidth = self.view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow
        layout.minimumLineSpacing = 6.0
        layout.sectionInset.left = 5
        layout.sectionInset.right = 5
        layout.itemSize = CGSize(width: widthPerItem, height: widthPerItem)
    } else {
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        let itemsPerRow: CGFloat = 2.0
        let paddingSpace: CGFloat = 2.0 * itemsPerRow
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow
        layout.minimumLineSpacing = 4.0
        layout.sectionInset.left = 0
        layout.sectionInset.right = 0
        layout.itemSize = CGSize(width: widthPerItem, height: widthPerItem)
    }
}


what you need is CGAffineTransform. So you can set their overall size like this:

    private func transformCell() {
            var offset : Float = 0.0

            for cell in numberCollectionView.visibleCells as! [MyCell] {

                offset = 0.07
                cell.transform = CGAffineTransform.identity
                cell.transform = CGAffineTransform(scaleX: CGFloat(offset), y: CGFloat(offset))

            }
     }

It will transform the visible cells into different size according to offset value and you can call it from scrollViewDidScroll

func scrollViewDidScroll(_ scrollView: UIScrollView) {

            transformCell()

    }