索引未从uicollectionviewcell传输到视图控制器

时间:2018-12-14 05:09:51

标签: indexing uicollectionview swift4 uicollectionviewcell optional

我下面的代码不起作用,并导致运行时错误。说明在展开Optional值时意外找到nil。我不知道是什么原因造成的。我不知道该如何解决可选问题。 cellforitemat的代码也已添加。

class antion : UICollectionViewCell {
      @IBOutlet var sam : UILabel!


      var deleagete : DataCollectionProtocoe?
      var index : IndexPath?

     @IBAction func press(){
            deleagete?.passData(indx: (index?.row)!)
     }

    @IBAction func delete(){
           deleagete?.deleteData(indx: (index?.row)!)
    }

 }


extension ViewController : DataCollectionProtocoe {
         func passData(indx: Int) {
              let vc = storyboard?.instantiateViewController(withIdentifier: "DetailVDC") as? DetailVDC
              vc?.name = people[indx].name!
              self.navigationController?.pushViewController(vc!, animated: true)

        }

       func deleteData(indx: Int) {
            people.remove(at: indx)
            cc.reloadData()
       }
}

protocol DataCollectionProtocoe {
         func passData(indx:Int)
         func deleteData(indx:Int)
}

class DetailVDC: UIViewController {
      var name = ""

      @IBOutlet var lbl : UILabel!

     override func viewDidLoad() {   
              lbl.text = name        
     }
}


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


     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! antion








    cell.index = indexPath
    cell.deleagete = self
    return cell
}

1 个答案:

答案 0 :(得分:0)

基于我从您的代码中无法理解的内容,看来您正在创建UICollectionViewCell实例,但未为单元格的委托属性设置任何值。

在控制器中创建集合视图单元格的实例时,将控制器分配给单元格的委托属性,如下所示:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = antion()
        cell.delegate = self // assuming the controller is the data source of the collection view
}