-1

In a storyboard there are 5 buttons. If I pressed any button, it will go into new storyboard. In new storyboard I just want to find which button was pressed to come here.

2 Answers2

0

You can create a State class where you can set the button type represented by an enum. Then access the value in the new storyboard.

struct State {
    static var btnType: ButtonType? 
}

enum ButtonType {
    case buttonA
    case buttonB
    // ..
}

In the main view controller where there are buttons, set the state on button tap.

class ViewController: UIViewController {
    func buttonADidTap(_ sender: Any) {
        State.btnType = .buttonA        
        // display the other view controller, say MyVCA
    }

    func buttonBDidTap(_ sender: Any) {
        State.btnType = .buttonB
        // ..
    }
}

In the child view controller, access the state data in viewDidLoad.

class MyVCA: UIViewController {

    override func viewDidLoad() {
        if let btnType = StateData.btnType {
            switch btnType:
            case .buttonA:
                // ...
        }
    }
}
John Doe
  • 2,225
  • 6
  • 16
  • 44
0

Add tag to button (in code or in storyboard) and send tag to next ViewController of pressed button.

class ViewController: UIViewController {

    override func viewDidLoad() {

        firstButton.tag = 1
        secondButton.tag = 2
        thirdButton.tag = 3
    }

    func goToNextVC(buttonTag: Int) {

        let vc = SecondVC()
        vc.buttonTag = buttonTag
        self.navigationController.push(vc, animated: true)
    }

    // action for all buttons if he just only send tag
    func buttonsDidTap(_ sender: Any) {
        goToNextVC(buttonTag: sender.tag)
    }
}

And Second ViewController

class SecondVC: UIViewController {

    var buttonTag: Int?

    override func viewDidLoad() {

        if buttonTag != nil {
            switch buttonTag:
            case 0:
            // ...
        }
    }
}