Search code examples
iosobjective-ccollectionview

How can I get CollectionViewCell content height based on content size?


I have few CollectionViewCell in my CollectionView. I need to adjust selected CollectionViewCell height after click on button. Please help.

   - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.section == 2) 
        {

            CGFloat h = self.collectionView.contentSize.height;


            if (isExpandedAboutUs && indexPath.row == 0)
            {
                return CGSizeMake(ScreenW, h); 
            }

            return CGSizeMake(ScreenW, 100);
        }
    }

self.collectionView.contentSize.height will return CollectionView height. What I need is selected cell content size.


Solution

  • You can try with below code on selection of cell:

     override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        let contentSize = cell?.contentView.bounds.size
        print(contentSize)
    }
    

    if you want to get size from another method then you may need to find the cell selected index path and pass index path accordingly. like:

    func yourMethod() {
        let selectedIndexPath = IndexPath(item: 0, section: 0)  //get your indexpath here
        let cell = collectionView?.cellForItem(at: selectedIndexPath)
        let contentSize = cell?.contentView.bounds.size
        print(contentSize)
    }
    

    As per print statements, the values you get for contentSize is the same size as the size you return in sizeForItemAtIndexPath method.