Search code examples
swiftuiviewcontrollersegue

How can I use a segue when I have two buttons that need to be pressed to activate it?


Basically, what I want to do is activate a certain segue when the user presses 2 different buttons. Unfortunately, I only know how to do it when 1 button is pressed. How can I achieve this? Thanks in advance!


Solution

  • I'm assuming you're supposed to press these buttons sequentially.

    Create 2 boolean variables in your ViewController and 2 IBAction methods, one for each button. When button A or B is pressed, set the corresponding boolean to true. When the second button (either A or B) is pressed, check if the other button's boolean variable is true. If yes, trigger the segue programmatically.

    You can create this segue between the two view controllers in the storyboard. Remember to give the segue a fitting name.

    Here's some example code.

     class MyViewController: UIViewController {
    
            var buttonAIsTapped: Bool = false
            var buttonBIsTapped: Bool = false
    
            override func viewDidLoad() {
                super.viewDidLoad()
            }
    
            @IBAction func buttonATapped(_ sender: UIButton) {
                buttonAIsTapped = true
                if buttonBIsTapped == true {
                   self.performSegue(withIdentifier: "SegueName", sender: self)
            }
            @IBAction func buttonBTapped(_ sender: UIButton) {
                buttonBIsTapped = true
                if buttonAIsTapped == true {
                   self.performSegue(withIdentifier: "SegueName", sender: self)
            }
        }