我的应用中有两个ViewController,分别为ViewController和ViewController2

在ViewController中,按钮设置为Present Modally segue to "ViewController2"
并且ViewController覆盖viewWillAppear

override func viewWillAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    print("will appear")
}

在ViewController2中,返回一个按钮
@IBAction func close(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

现在它仍然可以触发viewWillAppear,然后我从ViewController2回到ViewController

如果我将ViewController2的演示文稿从Full Screen更改为Over Current Context,则不会触发viewWillAppear
返回时如何触发一些代码?

最佳答案

您可以在不放弃情节提要的情况下做到这一点,但是您仍然必须在ViewCOntroller2中设置“将/会消失”处理程序:

class ViewController: UIViewController {
    ...
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? ViewController2 {
            (segue.destination as? ViewController2).onViewWillDisappear = {
                //Your code
            }
        }
    }
}

class ViewController2: UIViewController {
    var onViewWillDisappear: (()->())?

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        onViewWillDisappear?()
    }
    ...
}

关于ios - 从“Over Current Content” ViewController返回时如何触发一些代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48185775/

10-10 20:52