gpt4 book ai didi

ios - 调用 PoptoViewController 后从 UIController 的栈顶回调

转载 作者:行者123 更新时间:2023-11-28 07:42:03 24 4
gpt4 key购买 nike

我刚开始使用 swift 编程,但我很难理解 UIViewController 访问的工作原理。

基本上,我有一个 UIViewController,它在完成任务后会使用 PopToViewController 弹出并返回到另一个 VC。

我想将回调函数附加到 PopToViewController 操作,该操作调用位于新顶部 ViewController 上的函数。此 ViewController 已实例化,因此我不想创建新的。

基本上我现在有的是这样的

class CurrentController: UIViewController {

@IBAction func onButtonTap() {
popViewController(animated: true)
TargetController.dosomething()
}
}

目标 Controller (我想要执行该功能的 Controller )

class TargetController: UIViewCOntroller { 
func dosomething() { //I want to call this function right after pop happens without instantiating a new class
//do something
}
}

我尝试了一些访问方法,但大多数都是创建新实例或返回 nil。有什么简单的方法吗?

最佳答案

您的 CurrentController 中需要有 TargetController委托(delegate)。然后将 CurrentController 的实例传递给该委托(delegate)。现在您可以使用此委托(delegate)在弹出 CurrentViewController 时调用所需的方法。

class CurrentController: UIViewController {
var targetViewControllerDelegate: TargetController!

@IBAction func onButtonTap() {
CATransaction.begin()
navigationController?.popViewController(animated: true)
CATransaction.setCompletionBlock {
targetViewControllerDelegate.dosomething()
}
CATransaction.commit()
}
}

现在,当您推送 View Controller 时,您必须在 TargetController 中设置委托(delegate)。

class TargetController: UIViewController {

func functionWhereYouPush() {
let currentViewController = CurrentViewController()
currentViewController.targetViewControllerDelegate = self
navigationController?.pushViewController(currentViewController, animated: true)
}

func dosomething() {
//do something
}
}

如果您的 TargetController 不是直接父级,那么您将一直传递委托(delegate),直到到达子级或使用通知。

关于ios - 调用 PoptoViewController 后从 UIController 的栈顶回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com