【问题标题】:UICollectionView Custom Cell Size in SwiftSwift 中的 UICollectionView 自定义单元格大小
【发布时间】:2021-05-07 11:30:53
【问题描述】:

我想通过使用 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)
}
}

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 这是简单的布局。覆盖collectionView(_:layout:sizeForItemAt:) 就足够了。
  • 您错过了一个事实,即您有空间项,return CGSize(width: dimensions / 2, height: heightOfView) 应该只是 dimensions,因为您之前已经将它除以 2。
  • 当你可以用更少的行代码和组合布局来实现它时,为什么要使用 FlowLayout
  • @SandeepBhandari 我在这里没有使用合成布局,因为它只支持 iOS 13 或更高版本。

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以像这样设置 2 个部分:

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return 4
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        cell.backgroundColor = .blue
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return .init(width: view.frame.width - 16, height: 120)
        }
        return .init(width: view.frame.width / 2 - 32, height: 120)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 2014-09-02
      • 1970-01-01
      相关资源
      最近更新 更多