如何使用情节提要和swfit在一个collectionview中设置每个collectionview单元格大小?

问题描述 投票:0回答:1

我在viewController中有一个collectionView,在这个collectionView中,我有两个collectionView单元格,每个单元格都有自己的单元格标识符和大小。

我要做的是,当用户点击CardView按钮时,collectionView将显示标识符为“ CardCell”大小为300x400的单元格项目。

并且如果用户点击ListView,它将显示标识符为“ ListCell”大小为300x100的单元格项目。

目前,我正在检测要显示的单元格,我创建了枚举,变量cellIndex。

enum CellIndexType: Int {
    case cardView
    case listView
}
var cellIndex = 0

并且如果cellIndex等于0,vc将显示“ CardCell”,如果1,将显示“ ListCell”。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    var cell = Cell()

    if cellIndex == CellIndexType.cardView.rawValue {
        if let reusableCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as? Cell {
            cell = reusableCell
        }
    } else {
        if let reusableCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListCardCell", for: indexPath) as? Cell {
            cell = reusableCell
        }
    }
    return cell
}

这里是我的viewController,在一个CollectionView中有两个单元。

enter image description here

这是我的viewController的外观。

enter image description here

这是collectionView的属性检查器和大小检查器的方式看起来像。

enter image description hereenter image description here

但是使用我在情节提要和代码中的配置,它始终显示单元大小为300x400。

我可以通过哪种方式实现此逻辑?

swift xcode uicollectionview storyboard uicollectionviewcell
1个回答
0
投票

首先,必须在情节提要中将collectionView的像元大小设置为无。

enter image description here

第二,使用collectionView的sizeForItemAt func:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if self.cellIndex == 0{
        return CGSize(width: 300, height: 400)
    } else if self.cellIndex == 1{
        return CGSize(width: 300, height: 100)
    }
}

希望有帮助...

© www.soinside.com 2019 - 2024. All rights reserved.