jagtar singh
jagtar singh

Reputation: 35

Segue to SecondViewController without running the button code

I have this code in the button method.

@IBAction func sendMsg(_ sender: UIButton) {
    DataforChat.arr2.append(enterMsg.text!)
}

The button is connected to Second View Controller (by ctrl-drag segue). I was in debug mode when I found this problem. On pressing the button, the control of program directly go to viewDidLoad() method of second view controller without executing this line of code

DataforChat.arr2.append(enterMsg.text!)

I know we can programmatically present the second Controller. But is there any solution that It first run the code before shifting to another view. Thanks.

Upvotes: 1

Views: 131

Answers (2)

Harish Singh
Harish Singh

Reputation: 765

You are doing right, but not getting wat's may be the problem. But, you can try something like this

@IBAction func sendMsg(_ sender: UIButton) {

    DataforChat.arr2.append(enterMsg.text!)

    self.performSegue(withIdentifier: "NaviageToAnotherView", sender: sender)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "NaviageToAnotherView" {

        let swapVC = segue.destination as! HCSwapExerciseViewController

        // Do something here 
    }
}

Upvotes: 2

Michael Hulet
Michael Hulet

Reputation: 3499

You should manually perform the segue at the end of this method. Note that you'll need to connect the segue from the view controller to the next view controller, instead of the button to the next view controller

@IBAction func sendMsg(_ sender: UIButton) {
    DataforChat.arr2.append(enterMsg.text!)
    performSegue(withIdentifier: "Your segue identifier", sender: self)
}

Upvotes: 1

Related Questions