我已将uicollectionview放在uitableview中。在选择了一个位于表格视图单元格内的collectionview单元格后,我无法连接到另一个viewcontroller。
// if the user selects a cell, navigate to the viewcontroller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// we check did cell exists or did we pressed a cell
if let cell = sender as? UICollectionViewCell {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell") as! TestingTableView
// define index to later on pass exact guest user related info
let index = cell2.collectionView?.indexPath(for: cell)!.row
print(index as Any)
// if segue is guest...
if segue.identifier == "guest" {
// call guestvc to access guest var
let guestvc = segue.destination as! GuestCommunityViewVC
// assign guest user inf to guest var
guestvc.guest = communities[index!] as! NSDictionary
}
}
}
}
我在这一行收到错误:
let index = cell2.collectionView?.indexPath(for: cell)!.row
因为它说价值是零。有没有人知道更好的方法呢?
答案 0 :(得分:1)
以下是如何使用委托的示例:
1)在类声明之外创建一个协议:
protocol customProtocolName:class {
func pushToNewView(withData:[DataType])
}
注意:使用class以防止引用循环
2)在UITableViewCell内部创建一个委托,其中包含对UICollectionView的引用:
class customUITableViewCell {
weak var delegate:customProtocolName? = nil
}
3)在保存对UITableView的引用的UIViewController中,确保添加除类声明之外的协议并添加我们创建的函数以确保满足协议规范:
class customViewController: customProtocolName {
func pushToNewView(withData:[DataType]) {
//inside here is where you will write the code to trigger the segue to the desired new UIViewController
//You can take this new data and store it in this ViewController and then during the segue pass it along
}
}
4)在UITableViewDelegate函数“cellForRowAt”中,将customUITableViewCell中的委托设置为self:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customUITableViewCell
cell.delegate = self
return cell
}
5)在customUITableViewCell中,UICollectionView委托函数处理“didSelectItemAt”委托函数,你可以在那里触发协议函数:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.pushToNewView(withData:[DataType])
}
这是一个非常简单的示例,如果您想传递IndexPath,那么您可以修改函数来执行此操作。你也可以传回任何你想要的东西,但不限于此。