简体   繁体   English

UICollectionView Swift 中的自定义单元大小

[英]UICollectionView Custom Cell Size in Swift

I want to get the following Layout by using the UICollectionView, what's the best approach to achieve this.我想通过使用 UICollectionView 获得以下布局,实现这一目标的最佳方法是什么。

在此处输入图像描述

I have tried this approach but not getting desired outcome我已经尝试过这种方法,但没有得到想要的结果

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)
}
}

在此处输入图像描述

add UICollectionviewdelegateFlowlayout to ur class and use collectionView(_:layout:sizeForItemAt:) method... here u can return size of items depending on index path将 UICollectionviewdelegateFlowlayout 添加到您的 class 并使用 collectionView(_:layout:sizeForItemAt:) 方法...在这里您可以根据索引路径返回项目的大小

you can set 2 sections like this:你可以像这样设置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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM