【发布时间】:2019-01-06 11:00:08
【问题描述】:
场景:我有一个视图控制器 (vc1),它呈现另一个视图控制器 (vc2)。然后vc2呈现vc3。如何将 vc1 设置为 vc3 的委托?
情况:在 vc3 中,我打算跳回 vc1 并让它执行一些代码。但是,由于 vc3 实例是在 vc2 中创建的,所以 vc1 没有从 vc1 到 vc3 的直接链接。
这是我要实现的目标的简化图:
vc1
let vc2Instance = vc2()
navigationController?.pushViewController(vc2Instance)
class vc1: UIViewController, tellVC1ToDoSomethingDelegate {
func vc1DoSomething(withThis: String) {
// for instance: present another VC not currently in stack
let randomVC = RandomVC()
}
}
vc2
let vc3Instance = vc3()
navigationController?.pushViewController(vc3Instance)
vc3
protocol tellVc1ToDoSomethingDelegate() {
func vc1DoSomething(withThis: String)
}
class vc3: UIViewController {
weak var vc1Delegate: tellVC1ToDoSomethingDelegate?
func pushRandomVCWithString(myString: String) {
// code to dismiss view controllers up to vc1 in stack
if let vcStack = self.navigationController?.viewControllers{
self.navigationController?.popToViewController(vcStack[vcStack.count - 2], animated: true)
vc1Delegate.vc1DoSomething(withThis: myString)
}
}
这是我的问题: 如果我将 vc1 标记为 vc2 的委托(堆栈中只有 1 个 VC),我只需键入
let vc2Instance = vc2()
vc2Instance.vc1Delegate = self
当 vc1 中不存在 vc3 的实例时,我如何访问(vc1 的)self?将代表从 vc3 链接到 vc2 然后到 vc1 是唯一的出路吗?我想当中间有几个 vc 时这会很难看。
【问题讨论】:
-
你可以做委托链接,从 vc1 -> vc2 -> vc3 传递委托,然后 vc3 可以调用该委托并关闭 vc2 和 vc3
标签: ios swift delegates viewcontroller