seran seran - 3 years ago 163
iOS Question

Button state info

The question is similar to "how to pass data from different viewController" but in this case I need another information, I know how to pass the data from one viewController to another but I don't know how to tell to the second viewController a specific state of an object that is in the first view. In my case I have some buttons in the first view that go in.

button.isHidden = true


after the tap, I want to tell to the second viewController which buttons have been tap, maybe I've to create a variable that represents the status of the button, but I don't know how to do, someone can help me?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToLast" {

guard let vc = segue.destination as? FinalClass else { return }

let guest = segue.destination as! FinalClass

if let user = sender as? User {


}
}
}


where User can be something like

struct User {

var button1 = Button1 tapped
var button2 = Button2 tapped
ecc.

}

Answer Source

Let suppose you have two viewControllers - FirstViewController and SecondViewController.

So First,

Let Declare two Arrays in FirstViewController and SecondViewController something like -

var tappedButtonsArray = NSMutableArray() // In 'FirstViewController'
           AND
var previousViewTappedButtonsArray = NSMutableArray() // In 'SecondViewController'

And here is my code to add | remove tapped buttons to | from tappedButtonsArray in FirstViewController -

@IBAction func btnTapped(_ sender: UIButton) { // Single action for all buttons


    if (tappedButtonsArray.contains(sender)){ 

        tappedButtonsArray.remove(sender) // Remove previous tapped button on unselect
    }
    else{

        tappedButtonsArray.add(sender) // Add tapped button on select
    }


}

And Here is your perform segue method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToLast" {

        guard let secondViewController = segue.destination as? SecondViewController else { return }

        secondViewController.previousViewTappedButtonsArray = tappedButtonsArray
    }
}

I've done with a simple array concept without any model, so that you can understand the follow. I hope it'll help you to start with.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download