Evgeniy Kleban
Evgeniy Kleban

Reputation: 6965

expanding UICollectionViewCell on tap

I have UICollectionView that scrolls up vertically, and i want to change item height in tap. In default state, cell have a height of 2/3 screen height. I tried following:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
            if let cell = cell as? TutorialCell {
                let attribute = layout.layoutAttributesForItem(at: indexPath)
                attribute?.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width,
                                               height: UIScreen.main.bounds.size.height)
                collectionView.reloadItems(at: [indexPath])

            }
        print(indexPath.row)
    }

But it's not working.

Upvotes: 2

Views: 423

Answers (1)

Razi Tiwana
Razi Tiwana

Reputation: 1435

You can Achieve this by UICollectionViewDelegateFlowLayout method sizeForItemAt

Declare a variable

var selectIndex: Int = -1

In your didSelectItemAt add this

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.selectIndex = indexPath.row

    collectionView.reloadData()
}

Add an extension for UICollectionViewDelegateFlowLayout

extension YourViewController: UICollectionViewDelegateFlowLayout {

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

        let height = (self.selectIndex == indexPath.row ) ?
            UIScreen.main.bounds.size.height :
            (UIScreen.main.bounds.size.height * 2) / 3

        return CGSize(width:UIScreen.main.bounds.size.width, height:height)
    }
}

Upvotes: 1

Related Questions