Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing size of selected UICollectionView Cell

I have a simple UICollectionViewController that returns X amount of cells. I want to have it so when a cell is selected, that specific selected cell will change it's size and become larger in height as all of the other cells stay the same. How do I achieve this? Here's my code:

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.90, alpha: 1.0)

        collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId)
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.alwaysBounceVertical = true
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height = (view.frame.width) * 9 / 16
        return CGSize(width: view.frame.width, height: height + 50 + 50)
    }
}
like image 340
Daniel Dramond Avatar asked Jan 15 '17 14:01

Daniel Dramond


1 Answers

You can check to see if the indexPath from sizeForItemAt is selected. If it is, you return a different height otherwise return the standard height.

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    collectionView.performBatchUpdates(nil, completion: nil)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    switch collectionView.indexPathsForSelectedItems?.first {
    case .some(indexPath):
        return CGSize() // your selected height
    default:
        let height = (view.frame.width) * 9 / 16
        return CGSize(width: view.frame.width, height: height + 50 + 50)
    }
}
like image 198
Callam Avatar answered Oct 06 '22 01:10

Callam