JPJerry5
JPJerry5

Reputation: 127

How do I know in swift which button was pressed when different buttons lead to the same ViewController?

I have four buttons which all lead to the same view controller. I need to know which button was pressed, because the view controller is set up slightly different for each button. I tried the following: ViewController (called "SecondViewController") where one of the Buttons is pressed

    var index = 0

    @IBAction func Button1(_ sender: UIButton) {
        index = 1
    }
    @IBAction func Button2(_ sender: UIButton) {
        index = 2
    }
    @IBAction func Button3(_ sender: UIButton) {
        index = 3
    }
    @IBAction func Button4(_ sender: UIButton) {
        index = 4
    }


    func getIndex() -> Int{
        return index
    }

The view controller which will be opened afterwards

// to get functions from SecondViewController
var second = SecondViewController()

let index = second.getIndex()
print(index)

Unfortunately it always prints zero. I guess because I set the index to 0 in the beginning, but I do not understand why doesn't the value update, when the Button was pressed.

What can I do?

Upvotes: 1

Views: 896

Answers (3)

Charlie Cai
Charlie Cai

Reputation: 301

if I understand you correctly,you will definitely get index as 0.

var index = 0

@IBAction func Button1(_ sender: UIButton) {
    index = 1
}
@IBAction func Button2(_ sender: UIButton) {
    index = 2
}
@IBAction func Button3(_ sender: UIButton) {
    index = 3
}
@IBAction func Button4(_ sender: UIButton) {
    index = 4
}


func getIndex() -> Int{
    return index
}

above code is in SecondViewController, right?

then you call code below in another view controller (maybe FirstViewController)

// to get functions from SecondViewController
var second = SecondViewController()

let index = second.getIndex()
print(index)

so you get index out of the SecondViewController after it just was initialized and there is no way you can click on buttons and change index before second.getIndex().

Upvotes: -2

Taha Metin Bayi
Taha Metin Bayi

Reputation: 201

SecondViewController (Previous one which contains buttons)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let firstViewController = segue.destination as? FirstViewController {
        firstViewController.index = self.index
    }
}

FirstViewController (One should be displayed after buttons clicked)

var index: Int?

override func viewDidLoad() {
    super.viewDidLoad()

    print(index)
}

Upvotes: 1

Mohammad Assad Arshad
Mohammad Assad Arshad

Reputation: 1784

I guess you are using segues, so your segue is executing before your IBAction can update your index value. There is a similar question & solution here

So to fix this give your segue an identifier, and call performSegueWithIdentifier from within your IBAction methods.

Upvotes: 2

Related Questions