Home > Software engineering >  Data from 3 different buttons on a VC to a second VC to be displayed as title
Data from 3 different buttons on a VC to a second VC to be displayed as title

Time:12-08

I have have two View Controllers. In my VC1 I have 3 buttons that will represent 3 different colors from different colors (Black, Pink, and Orange). The action outcome I want is that, when I click on whichever button, it will take me to my VC2 which would be displaying the name of the button as the title.

Let's say I tap on the Black button. Right after I do it, it would take me from VC1 to VC2 and the title would read Black and it would be the same for the rest of the buttons (Pink, and Orange.)

This is what I have so far:

 @IBAction func myBlackButton(_ sender: Any) {
    performSegue(withIdentifier: "VCColor", sender: self)
    
}

@IBAction func myPinkButton(_ sender: Any) {
    performSegue(withIdentifier: "VCColor", sender: self)
    
}

@IBAction func myOrangeButton(_ sender: Any) {
    performSegue(withIdentifier: "VCColor", sender: self)
    
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    if segue.identifier == "VCColor" {
        
        if let destino = segue.destination as? ViewControllerColors {
            
            destino.titulo = "Negro"
            
        }
        
    }
    
}

}

CodePudding user response:

-> create a variable on VC2

var color: String?

-> Create a function VC1 to send data to another

func buttonTap(Color: String) {

let vc = let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "VC2") as? VC2
vc.color = Color
self.navigationController?.pushViewController(vc!, animated: true)

}

-> call the function in each button

@IBAction func myOrangeButton(_ sender: Any) {
    buttonTap(Color:"Orange");
}
  • Related