Passing data back from view controllers Xcode
A couple of weeks ago I asked this question and got a very detailed explanation. Now I would like to pass data back to the first ViewController but I keep getting stuck using the same method. I have a modal of the first VC to the second, where I would like to edit an array of strings, which will be showed on the first view again. So on my first view I have an array of data, which should be passed to the second so edit fields show the current information after which the user has to be able to edit the contents of the array and pass that data back to the first where it is shown on labels. I'm using Swift.
My code:
(in ViewController.swift:)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
let secondVC = segue.destinationViewController as SecondViewController
secondVC.namesPlayers = self.namesPlayers
}
(in SecondViewController.swift:)
override func viewDidLoad() {
super.viewDidLoad()
labelFirstPlayer.text = namenSpelers[0]
}
Thank you
You need to use a delegate. Here is an example how do use a delegate in Swift.
On your first ViewController, set your delegate when you load the second VC:
For example, if you are using the Storyboard Editor:
var secondViewController = (segue.destinationViewController.visibleViewController as MySecondViewControllerClass)
secondViewController.delegate = self
Write a Protocol and define a func to write you values back
For example, create a file called "Protocol.swift" and write something like that:
protocol writeValueBackDelegate {
func writeValueBack(value: String)
}
Add the function to your FirstViewController
func writeValueBack(value: String) {
// Or any other function you need to transport data
}
And to your ViewControllerClass
class ViewController: UIViewController, writeValueBackDelegate
The above line will not work if you have not implemented all of the methods in ViewController
that you defined in your protocol file.
Go to the Second View Controller, and add the delegate here:
class SecondViewController: ViewController {
// Delegate for FirstViewController
// Declare as weak to avoid memory cycles
weak var delegate: writeValueBackDelegate?
}
On your Second View Controller, you can now use this to call the func in the first View Controller an pass data.
delegate?.writeValueBack("That is a value")