如果这是您正在寻找的东西,那么它很容易做到UICollectionViewFlowLayout
![最终结果](https://i.stack.imgur.com/c87LI.png)
我使用单元格的比例为 1:1,因此宽度和高度相同,您可以使用填充和项目间距等来获得所需的效果。
您的控制器必须符合UICollectionViewDelegateFlowLayout
协议
在我的测试应用程序中,我执行了以下操作:
override func viewDidLoad() {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = 5
let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ident")
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let item = indexPath.item
let width = collectionView.bounds.size.width
let padding:CGFloat = 5
if item < 2 {
let itemWidth:CGFloat = (width - padding) / 2.0
return CGSize(width: itemWidth, height: itemWidth)
} else {
let itemWidth:CGFloat = (width - 2 * padding) / 3.0
return CGSize(width: itemWidth, height: itemWidth)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ident", for: indexPath)
cell.backgroundColor = .red
return cell
}