gpt4 book ai didi

swift - UICollectionView 不断崩溃,除非我设置indexpath.items = 1

转载 作者:行者123 更新时间:2023-11-30 12:47:40 29 4
gpt4 key购买 nike

您好,我有两个代码,其中一个可以工作,而另一个则不能,有人可以解释一下为什么吗?第一个功能有效,而第二个则无效。我正在尝试生成一个单元格作为 PayNowCell 类型,并将其后的每个单元格生成为 CheckOutCell 类型。但是,它只允许我将第一个单元格作为 CheckOutCell,将第二个单元格作为 PayNowCell,并将后面的每个单元格作为 CheckOutCell。谢谢!!!错误是索引超出范围。它指向这条线
cell.item = checkout[indexPath.item]。

本质上,我有一个动态数组 checkout[],我只是想在 checkout[] 增长和收缩时在每个 checkoutcell 顶部插入一个名为 paynow 的描述单元

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

if indexPath.item == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "paynow", for: indexPath) as! PayNowCell //init cells
return cell
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CheckoutCell //init cells
cell.item = checkout[indexPath.item]
return cell
}
}

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

if indexPath.item == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "paynow", for: indexPath) as! PayNowCell //init cells
return cell
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CheckoutCell //init cells
cell.item = checkout[indexPath.item]
return cell
}
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (checkout.count + 1) //init number of cells
}

最佳答案

尝试使用此数组来管理您的 Collection View

var array = [0,[]]

然后添加

array[1] = [your array for index 1]

您可以在 Collection View 中添加管理多单元格的部分:-

func numberOfSections(in collectionView: UICollectionView) -> Int{
return (array[section] as AnyObject).count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array[1].count
}


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

if indexPath.item == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "paynow", for: indexPath) as! PayNowCell //init cells
return cell
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CheckoutCell //init cells
let checkout = array[1] // pass here array
guard checkout.count != 0 else {
return cell
}
cell.item = checkout[indexPath.item]
return cell
}
}

关于swift - UICollectionView 不断崩溃,除非我设置indexpath.items = 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414150/

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