首页 > 解决方案 > Swift 中的 UICollectionView 自定义单元格大小

问题描述

我想通过使用 UICollectionView 获得以下布局,实现这一目标的最佳方法是什么。

在此处输入图像描述

我已经尝试过这种方法,但没有得到想要的结果

func collectionView(_ collectionView: UICollectionView, layout 
collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: 
IndexPath) -> CGSize {
let totalWidth = collectionView.bounds.size.width
let totalHeight = collectionView.bounds.size.height
let heightOfView = totalHeight / 3
let numberOfCellsPerRow = 2
let dimensions = CGFloat(Int(totalWidth) / numberOfCellsPerRow)
if (indexPath.item == 0) {
    return CGSize(width: collectionView.bounds.size.width, height: heightOfView)
} else {
    return CGSize(width: dimensions / 2, height: heightOfView)
}
}

在此处输入图像描述

标签: iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

解决方案


将 UICollectionviewdelegateFlowlayout 添加到您的类并使用 collectionView(_:layout:sizeForItemAt:) 方法...在这里您可以根据索引路径返回项目的大小


推荐阅读