不幸的是,这并不容易。
您想要查看的是 NSNotificationCenter 甚至更好: - 代表。
如果你想更好地理解 Delegates,我推荐这个教程:http://www.raywenderlich.com/75289/swift-tutorial-part-3-tuples-protocols-delegates-table-views
如果您不想阅读所有内容,我会尽力在这里解释。
假设您有两个视图控制器:mainVC 和 otherVC。
在otherVC的类定义之上,添加如下代码:
protocol OtherVCDelegate {
func cellClicked()
}
在otherVC的类里面,添加如下属性:
var delegate: OtherVCDelegate?
在 didSelectRow 中(或执行代码的地方),添加以下代码:
self.delegate?.cellClicked()
现在,回到 mainVC:通过像这样将 mainVC 添加到类中,使 mainVC 符合这个委托:
class MainViewController: UIViewController, DetailDelegate {
}
在 MainViewController 添加委托函数并在其中放置您要执行的函数:
func cellClicked() {
println("Cell was clicked")
myFunc()
}
您要做的最后一件事是让 MainViewController 成为 OtherViewController 的委托。这必须在您从 mainVC 访问 otherVC 的地方完成。假设它是在 prepareForSegue 中完成的:
if segue.identifier == "showDetail" {
(segue.destinationViewController as DetailViewController).delegate = self
}
一开始有点复杂,但是一旦你掌握了它,那就是在公园里散步。