首页 > 解决方案 > 如何根据子图像的纵横比设置 UICollectionViewCell 的高度?

问题描述

我想在集合视图中显示不同尺寸(800x600、800x800、800x1200 等)的图像(每个图像都是一个单元格)。单元格的宽度是静态的,等于集合视图的宽度,但高度需要是动态的,根据显示的图像计算,这样我们就不会裁剪任何艺术品!

我正在使用UICollectionViewCompositionalLayout和加载来自专用笔尖的传感器,如下所示:

collectionView.register(UINib(nibName: "Image", bundle: nil), forCellWithReuseIdentifier: "ImageCell")

接着

private func cell(collectionView: UICollectionView, indexPath: IndexPath, item: Item) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell...
    cell.setup(...)
    return cell
}

唯一的ImageCell一个图像视图被限制在其超级视图(单元格的contentView):

细胞

此单元格的布局使用.estimated高度:

private func createImageSectionLayout() -> NSCollectionLayoutSection {
    let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(20)))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(20)), subitems: [item])
    let section = NSCollectionLayoutSection(group: group)
    section.interGroupSpacing = 16
    section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 16, trailing: 16)
    return section
}

最后,我使用ScaledHeightImageView了一个UIImageView子类,它根据图像的纵横比(取自此处)计算内在大小。

现在的问题是,当我设置单元格并计算内在大小时,imageView 的宽度是来自 storyboard的宽度,而不是来自 parent的宽度UICollectionView,所以我的单元格的高度总是错误的。

有人可以帮助我了解我的设置有什么问题吗?

我尝试过:

但似乎没有任何效果。

标签: iosswiftuicollectionviewcellnibuicollectionviewcompositionallayout

解决方案


推荐阅读