gpt4 book ai didi

ios - 如何设置自定义collectionView Cell Frame?

转载 作者:行者123 更新时间:2023-11-30 11:08:34 25 4
gpt4 key购买 nike

我希望第一个 UICollectionViewCell 达到屏幕的全宽,然后 UICOllectionViewCell 为 2*2。

为此我尝试了下面的代码。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 0 {
let cell : FirstCell = collectionView.dequeueReusableCell(withReuseIdentifier: "FirstCell", for: indexPath) as! FirstCell

cell.layoutSubviews()
return cell
}
else {
let cell : SecondCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SecondCell", for: indexPath) as! SecondCell

cell.layoutSubviews()
return cell
}
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

if indexPath.item == 0 {
let width = (UIScreen.main.bounds.size.width - 16)
return CGSize(width: width, height: 200)
}
else {
let width = (UIScreen.main.bounds.size.width - 24) / 2
let height = (UIScreen.main.bounds.size.width * 200) / 320
return CGSize(width: width, height: height)
}
}

但是输出如下。

enter image description here

要求:第一个绿色单元格为全宽,第二个黄色单元格不是来自中心,而是来自左侧,第三个、第四个等单元格为 2*2

任何帮助将不胜感激。

提前致谢。

最佳答案

要实现此目的,您应该在 Collection View 中选取 3 个部分。

  1. 第 1 - 1 个单元格
  2. 第 2 - 1 个单元格(宽度应小于收集单元格可用宽度的一半)
  3. 第 3 部分 - 您想要的单元格数量
<小时/>
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return section == 2 ? 4 : 1
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch indexPath.section {
case 0:
return CGSize(width: UIScreen.main.bounds.width - 20, height: 200)
case 1:
return CGSize(width: (UIScreen.main.bounds.width - 30) / 2, height: 200)
default:
return CGSize(width: (UIScreen.main.bounds.width - 30) / 2, height: 200)
}
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectioncell", for: indexPath)
cell.backgroundColor = .red
return cell
}
}

您的 View 将如下所示:

enter image description here

关于ios - 如何设置自定义collectionView Cell Frame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52442509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com