如何从同一个按钮将数据传递给多个viewcontrollers

时间:2017-05-28 15:12:23

标签: swift xcode segue viewcontroller

这是stackoverflow上最受欢迎的问题之一的另一个版本。抱歉。谢谢。

我有一个有30个按钮的viewcontroller。这些按钮中的每一个都可以基于从先前视图控制器发送的变量而切换到20个视图控制器中的一个。

我知道如何将数据从一个viewcontroller发送到另一个viewcontroller,我知道如何让一个按钮连接到多个viewcontrollers依赖于传递的变量,但我不知道如何从一个按钮传递一个变量从变量...

指定任何viewcontroller

我的viewcontroller看起来像这样:

@IBAction func didTapButton(_ sender: UIButton) {
    if passedvariable == "A" {
        performSegue(withIdentifier: "ToA", sender: self)
    if passedvariable == "B" {
        performSegue(withIdentifier: "ToB", sender: self)
    }

我尝试添加这样的东西......

@IBAction func didTapButton(_ sender: UIButton) {
    if passedvariable == "A" {
        performSegue(withIdentifier: "ToA", sender: self)       
            let send = segue.destination as! AViewController
            send.NewVariableToSend = (sender as! UIButton).title(for: .normal)!}
    }

但那不起作用......我觉得我已经接近了,但还无法连接点。非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

您如何通过UIButton的IBAction方法访问实际的segue? 这种方法是错误的。使用PrepareForSegue方法将数据传递给下一个ViewController。它是一种预定义的方法,因此您只需在ViewController类中覆盖此方法。

试试这个.. 注意: 如果您尝试将任何nil值传递给下一个guard letViewController用于摆脱崩溃。

@IBAction func didTapButton (_ sender: Any) {
        //First get the clickedButton Object if you do not have IBOutlet of that button
        guard let clickedButton = sender as? UIButton else {return}
        //Pass the clicked button to Segue perform as a sender
        self.performSegue(withIdentifier: "yourSegueIdentifier", sender: clickedButton)

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "yourSegueIdentifier" {
            //Now get you destination viewcontroller and type cast it into your desired ViewController class
            guard let nextVC = segue.destination as? YourViewController else {return}
            //Now convert the sender into your clicked button because you have previously set the clickedButton as sender when you try to perform this segue
            guard let clickedButton = sender as? UIButton else {return}
            //Now Simply assign this to nextVC
            nextVC.button = clickedButton
        }

    }