除非我设置indexpath.items = 1,否则UICollectionView会一直崩溃

时间:2017-01-01 08:00:02

标签: swift xcode uicollectionview swift3

嗨我有两个代码,因为某人的原因是1有效,而另一个代码不能有人请解释原因吗?第一个功能起作用,而第二个功能不起作用。我尝试生成一个单元格作为PayNowCell类型,然后生成每个单元格作为CheckOutCell类型。但是,它只允许我将第一个单元格作为CheckOutCell,第二个单元格作为PayNowCell,将每个后续单元格作为CheckOutCell。谢谢!!!错误是索引超出范围。它指向这条线        cell.item = checkout [indexPath.item]。

基本上我有一个动态数组checkout [],我只是试图在checkout []增长和收缩时插入一个名为paynow ontop of each checkoutcell的描述单元

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
}

1 个答案:

答案 0 :(得分:0)

尝试使用此数组来管理您的集合视图

var array = [0,[]]

然后添加

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

您可以在集合视图中添加管理多单元格的部分: -

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