How can I pass information to a Uilabel in the second swift view controller?

advertisements

I'm fairly new to swift and i'm just trying to learn the different techniques.

The Situation: I have 2 view controllers. View controller number 1 consist of four buttons (north, south, east, west) for example. Lets say you click on the north button. It should take you to View controller number 2 and the UiLabel in View controller 2 should be displaying the name of whatever button that was pressed ("North" in this case). I know that when you're passing information forward, you should use the "prepare for segue" method but is there a way to do this with all 4 buttons? I also have a optional string variable in View Controller 2 that should catch the information being passed from View controller 1. I've searched everywhere but i haven't gotten an answer on this.

The code i have currently in view controller 1:

@IBAction func north(sender: UIButton) {

}
@IBAction func east(sender: UIButton) {

}
@IBAction func west(sender: UIButton) {

}
@IBAction func south(sender: UIButton) {

}

The Code i have currently in View Controller 2:

@IBoutlet weak var label2: UILabel!

var updateTheLabel: String?
override func viewDidLoad() {
super.viewDidLoad()
label2.text = updateTheLabel!
}

Question: how do i perform a segue with all four buttons to go to the Second view controller and update the UiLabel respectively?


To add to @ahmad-farrag's solution

You can modify your IB Actions to pick up the text from the button that is pressed

var buttonText = ""

@IBAction func north(sender: UIButton) {
   buttonText = sender.currentTitle.text
}
@IBAction func east(sender: UIButton) {
   buttonText = sender.currentTitle.text
}
@IBAction func west(sender: UIButton) {
   buttonText = sender.currentTitle.text
}
@IBAction func south(sender: UIButton) {
   buttonText = sender.currentTitle.text
}

This will assign the text from the buttons to the buttonText variable. Now in your prepareForSegue let us assume the two view controllers are connected by a segue with an identifier secondControllerSegue.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if segue.identifier == "secondControllerSegue" {
      let controller = segue.destinationViewController as! SecondViewController
      controller.updateTheLabel = buttonText
   }
}

This will send the buttonText we have captured earlier to the secondViewController