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



下面的代码不起作用,导致运行时错误。Stating在展开可选值时意外发现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
}

根据我从您的代码中所能理解的一点,看起来您正在创建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
}

最新更新