如何通过代理实现从TableViewCell内嵌CollectionViewCell跳转到其他ViewController
问题根因
你在ViewController中定义的全局customTableViewCell实例和TableView实际复用渲染的CustomTableViewCell是两个完全独立的实例,你仅给全局无意义的空实例设置了delegate,真实显示在列表中的cell的delegate从未被赋值,因此点击触发时代理为nil,方法不执行。
此外还有一个隐藏问题:当前代理协议未声明为类专属,delegate未用weak修饰,容易引发循环引用内存泄漏。
修复步骤
1. 修改CustomTableViewCell的代理声明
// 协议增加AnyObject约束,声明为类专属 protocol CustomTableViewCellDelegate: AnyObject { func passTheCurrent(tableIndex: Int, collectionViewIndex: Int) } class CustomTableViewCell: UITableViewCell { @IBOutlet weak var collectionView: UICollectionView! // delegate用weak修饰,避免循环引用 weak var delegate: CustomTableViewCellDelegate? // 其余原有代码保持不变 }
2. 修改ViewController的相关代码
首先删除两行无效代码:
- 全局变量声明
var customTableViewCell = CustomTableViewCell() - viewDidLoad中的
customTableViewCell.delegate = self
然后修改cellForRowAt方法,给真实出队的cell设置delegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let customCell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell // 给当前真实渲染的cell赋值delegate customCell.delegate = self return customCell }
可选优化
如果需要拿到点击的CollectionViewCell所属的TableView行索引,可在CustomTableViewCell中新增var tableIndex: Int?属性,在cellForRowAt中赋值customCell.tableIndex = indexPath.row,代理方法触发时传递这个值即可,不需要写死为0。
如果修复后代理方法已经能正常打印,但跳转无反应,检查ObjectSceneViewCtrl的初始化方式是否正确:如果是XIB创建的控制器需要用ObjectSceneViewCtrl(nibName: "对应XIB名", bundle: nil)初始化,Storyboard创建的需要用instantiateViewController(withIdentifier:)方法初始化。
内容的提问来源于stack exchange,提问作者Mehul D
相关产品推荐
相关产品推荐

