![](/img/trans.png)
[英]How do I dynamically size UICollectionViewCell's height based on content?
[英]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.