首页 > 解决方案 > 关闭后对前一个视图控制器的操作

问题描述

我有两个视图控制器。通过按 button1,我从 VS_1 更改为 VS_2。通过按下按钮 2,我转到视图控制器 1。此时我需要 button1 将其颜色更改为红色。怎么做?

class VC_1: UIViewController{

    ..........
    var button1 = UIButton()
    button1.backgroundColor = .green

    @IBAction func goToVC_2(_ sender: Any) {

        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vC2 = storyBoard.instantiateViewController(withIdentifier: "VC2") as! VC_2

        self.present(vC2, animated: true, completion: nil)
    }
}

class VC_2: UIViewController{

    ..........
    var button2 = UIButton()
    button2.backgroundColor = .green

    @IBAction func goToVC_1(_ sender: Any) {

        self.dismiss(animated: true, completion: nil)
    }

}

标签: iosswiftuikit

解决方案


您可以通过回调、委托等方式完成。

通过回调:

@IBAction func goToVC_2(_ sender: Any) {

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vC2 = storyBoard.instantiateViewController(withIdentifier: "VC2") as! VC_2

    vC2.didTapButton = {
        // change color here 
    }
    self.present(vC2, animated: true, completion: nil)
}


var didTapButton: () -> Void = { }

@IBAction func goToVC_1(_ sender: Any) {
    didTapButton()
    self.dismiss(animated: true, completion: nil)
}

推荐阅读