如何根据内容大小获取 CollectionViewCell 内容高度?

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

我的 CollectionView 中几乎没有 CollectionViewCell。单击按钮后,我需要调整选定的 CollectionViewCell 高度。请帮忙。

   - (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 会 return CollectionView 身高。我需要的是选定的单元格内容大小。

您可以尝试使用以下代码选择单元格:

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

如果您想通过另一种方法获取大小,那么您可能需要找到单元格选择的索引路径并相应地传递索引路径。喜欢:

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)
}

根据 print 语句,您为 contentSize 获得的值与您在 sizeForItemAtIndexPath 方法中 return 的大小相同。