如何在不相互隔离的viewControllers之间传递信息?

时间:2017-07-12 11:09:42

标签: swift xcode

我有一个非常复杂的函数在一个视图控制器中生成一个值(让我们称之为<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Divs</title> </head> <body> <section> <div class="holder"> <div class="other-div fixed">This div should stay fixed for a while</div> <div class="sticky">This div will become fixed on scroll</div> </div> </section> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> </body> </html>)。此值在firstVC中使用,但我还希望稍后在其他视图控制器中使用此值(我们将其称为firstVC)。我知道我可以设置一个协议来重新运行该函数,但这只需要额外的时间,我宁愿只传递该值。 thirdVCfirstVC之间不存在segue,thirdVC将被打开并使用该值的时间未知,将在稍后的某个时间。 (我仍然可以通过以下方式访问thirdVCthirdVC - &gt; firstVC - &gt; secondVC)。我想可以设置如下:

thirdVC

//In firstVC var currentVal: String = "Hello" @IBAction func button(_ sender: UIButton){ let storyBoard = UIStoryboard(name: "Main", bundle: nil) let thirdVC: thirdVC = storyBoard.instantiateViewController(withIdentifier: "thirdVC") thirdVC.passedValue = currentVal } passedValue中的变量。但是,这并未传递任何信息,因为当我尝试检查thirdVC passedValue thirdVC上的viewDidLoad()时它是空的...我也尝试稍后通过检查值按钮(确保在传递信息之前viewDidLoad()运行不是问题)并且它仍然是空的。

1 个答案:

答案 0 :(得分:1)

您需要在设置vc时设置该值,可以使用didSet完成,如下所示。

var currentVal: String = "Hello"

@IBAction func button(_ sender: UIButton){
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let thirdVC: thirdVC = storyBoard.instantiateViewController(withIdentifier: "thirdVC")
    storyBoard.instantiateViewController(withIdentifier: "thirdVC")
    thirdVC.passedValue = currentVal
    self.present(thirdVC, animated: true, completion: nil)
}

第三个vc ..

class thirdVc: UIViewController {

    var someValue: String? = nil

    // MARK: - Value to set when passed
    var passedValue: String! {
        didSet {
            self.someValue = passedValue
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        print(self.someValue) // "Hello"
    }

}