ios - 从另一个类/方法调用委托(delegate)方法(特别是 didSelectRowAtIndexPath)

标签 ios swift uitableview delegates

假设我有一个 tableViewController 和以下内容:

class tablVC: UITableViewController {
...
func thingsToDo() {
doSomeGenericStuff(indexPath: anIndexPath, targetTableView: self.tableView [, the Delegate: UITableViewDelegate]) //the part in parentheses is explained blow
}
...
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// do stuff
}
...

}

doSomeGenericStuff() 是类之外的方法,因为有一堆完全不同的 tableViewControllers 都想使用这个方法。

我真正想通过这个方法做的是调用:

tableView(TableView: UITableView, didSelectRowAtIndexPath: NSIndexPath) 

我已经像下面这样设置了它,我也尝试过直接将它传递给委托(delegate)。

func doSomeGenericStuff(indexPath: NSIndexPath, targetTableView: UITableView [, theDelegate: UITableViewDelegate]) {
...
//call didSelectRowAtIndexPath here
...
}

使用括号中的代码我可以获得自动完成功能,但以下代码会崩溃。

theDelegate.tableView!(targetTableView, didDeselectRowAtIndexPath: indexPath)

有没有办法让它以任何方式工作?

更新:错误

2016-06-12 12:49:12.390 AppName[14221:3670062] -[AppName.tableVC tableView:didDeselectRowAtIndexPath:]: unrecognized selector sent to instance 0x14c6ea370
2016-06-12 12:49:12.392 AppName[14221:3670062] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppName.tableVC tableView:didDeselectRowAtIndexPath:]: unrecognized selector sent to instance 0x14c6ea370'

最佳答案

我需要传递tableViewController,而不是tableView。

我想我会把它留在这里作为对范围的提醒,并提醒自己注意它,以及一些关于公开羞辱的事情。

            targetTableViewController.tableView.delegate?.tableView!(targetTableViewController.tableView, didSelectRowAtIndexPath: indexPath)

关于ios - 从另一个类/方法调用委托(delegate)方法(特别是 didSelectRowAtIndexPath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37777034/

相关文章:

ios - MKMapView:如何将 MKUserLocationView(蓝点)置于最前面?

ios - 是否可以在 UISearchBar 键盘中添加键盘预测选项

swift - GoogleCast iOS 发件人,v4,不发送消息

ios - UITableView 的值?

ios - 如何使用动态单元格设置 View (UITableview)的背景?

ios - 应用未运行时如何处理远程通知

ios - 在 UITableViewCell 中使用 AlamofireImage

iOS 14 如何触发本地网络对话框并检查用户答案?

ios - 根据来源不同,Unwind Segue 也不同

ios - 运行测试时静态变量变为零