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

标签 ios swift uiviewcontroller

我刚开始使用 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/

相关文章:

ios - 不使用 navigationController 的 SWrevealViewController

ios - 为什么在使用 init(barButtonSystemItem, target, action) 初始化时 UIBarButtonItem 的目标设置为 nil?

ios - 如何在一周中的特定几天重复本地通知(iOS Swift 3)

ios - 为 UIWindow 选择适当的级别以启用与其背后的 Controller 的交互

ios - iOS和Cocos2d:收到内存不足警告,只有20 MB的分配并且没有正在运行的其他应用程序

ios - Objective-C UIScrollView 不滚动

ios - 禁用 WiFi 的多点连接

ios - 如何在 iPad 上使 UITextView 大小相同(Swift)

ios - 如何在 Xcode 中使用 for 循环声明属性

iphone - iOS 中每个 View Controller 的静态 View