在Swift 4中修改和使用跨文件的变量

时间:2018-03-13 21:27:31

标签: swift

我有两个视图控制器。在第一个中,让我们称之为ViewControllerA,我有一个Button。在第二个视图控制器中,让我们称之为ViewControllerB,我有一个View。 ViewControllerA中的Button对ViewControllerB执行segue。通常,ViewControllerB中的View将其isHidden属性设置为true。

当我单击ViewControllerA中的Button时,ViewControllerB中的View是否将其isHidden属性更改为false?

这就是我对ViewControllerA

的看法
class ViewControllerA: UIViewController {

var buttonPressed : Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func theButton(_ sender: Any) {
    buttonPressed = true

    performSegue(withIdentifier: "goToControllerB", sender: self)
}

}

这就是我对ViewControllerB所拥有的:

class ViewControllerB: UIViewController {

@IBOutlet weak var myView: UIView!

var isButtonPressed : Bool = ViewControllerA().buttonPressed


override func viewDidLoad() {
    super.viewDidLoad()

    if isButtonPressed == true {

        myView.isHidden = false
    }
    else {

        myView.isHidden = true
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


}

2 个答案:

答案 0 :(得分:0)

只需在ViewControllerA中覆盖prepare(for:sender :),如下所示:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard segue.identifier == "goToControllerB", let destination = segue.destination as? ViewControllerB else { return }

    destination.isButtonPressed = true
}

然后,在ViewControllerB中的viewDidLoad()函数内,设置视图的可见性:

myView.isHidden = !isButtonPressed

答案 1 :(得分:0)

prepareForSegue中实施ViewControllerA方法,如下所示:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "goToControllerB" {
       if let destinationVC = segue.destination as? ViewControllerB {
           destinationVC.isButtonPressed = false
       }
   }
}

ViewControllerB中,更改变量:

var isButtonPressed: Bool?