I'm learning how to pass data between controllers when a button is pressed, so I'm following this answer: Pass data through segue, But I can't make it work, I have 3 buttons and I want to know which button was pressed, so my code in HomeView is:
var buttonPressed: String?
@IBAction func newsTapped(_ sender: Any) {
buttonPressed = "news"
self.performSegue(withIdentifier: "showNext", sender: buttonPressed)
}
@IBAction func tipsTapped(_ sender: Any) {
buttonPressed = "tips"
self.performSegue(withIdentifier: "showNext", sender: buttonPressed)
}
@IBAction func otherTapped(_ sender: Any) {
buttonPressed = "other"
self.performSegue(withIdentifier: "showNext", sender: buttonPressed)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let data = buttonPressed
if let destinationViewController = segue.destination as? TableViewController {
destinationViewController.origin = data
}
And the code in destinationView (TableViewController) is:
var origin: String?
override func viewDidLoad() {
if let dataRecived = origin
switch dataRecived {
case "news":
print("News")
case "tips":
print("Tips")
case "other":
print("Other")
}
}
When I click any of the buttons, it takes me to the TableViewController, but doesn't print anything, I added the If let, since it crashed when the statement was: if let dataRecived = origin
, now it never gets inside the if let statement. If I show the content of the variable (mouse over variable in xCode) it shows: ""
Any ideas why it isn't working? Not sure if it has something to do, but HomeView is a ViewController, linked to a Navigation controller that has a TableView (which is destinationView. Thanks for your help