DisplayScoreController

DisplayScoreController

如何从DisplayScoreController调用ViewController中定义的playAgain()函数?

ViewController.swift

class ViewController: UIViewController {

    func playAgain() {
        print("Play Again")
    }
}


DisplayScoreController.swift

class DisplayScoreController: UIViewController {

    @IBAction func playAgain(_ sender: Any) {
        dismiss(animated: true, completion: nil)

    // I want to call playAgain() in ViewController
}

最佳答案

您可以通过将闭包传递给DisplayScoreController来关闭控制器并调用playAgain()

在下面的示例中,我在prepare(for:sender:)中设置了该闭包。如果您不使用Segue启动DisplayScoreController,则可以在实例化DisplayScoreController之后和展示它之前分配此闭包。

在我的示例中,当用户按下Done中的DisplayScoreController按钮时,我触发了闭包的调用。您可以在要触发该操作的任何地方拨打self.goPlayAgain?()呼叫。

class ViewController: UIViewController {

    func playAgain() {
        print("Play Again")
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showScore" {
            if let dvc = segue.destination as? DisplayScoreController {
                // assign closure to goPlayAgain property
                // of destination view controller to dismiss
                // the destination and call playAgain()
                dvc.goPlayAgain = {
                    self.dismiss(animated: true, completion: nil)
                    self.playAgain()
                }
            }
        }
    }

}

class DisplayScoreController: UIViewController {

    // property to hold closure which dismisses this
    // view controller and calls playAgain() in
    // ViewController
    var goPlayAgain: (() -> ())?

    // Time to return to ViewController and call playAgain()
    @IBAction func done(_ sender: UIButton) {
        self.goPlayAgain?()
    }

}

关于ios - 如何在不使用委托(delegate)的情况下从辅助 View Controller 快速调用在主ViewController中定义的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47897642/

10-11 10:57