繁体   English   中英

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

[英]How can I get CollectionViewCell content height based on content size?

我的CollectionViewCell中没有几个CollectionView 单击按钮后,我需要调整选定的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将返回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)
}

根据打印语句,您为contentSize获得的值与您在sizeForItemAtIndexPath方法中返回的大小相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM