I\'ve been struggling for a few days now with passing an array from my SecondViewController
to my FirstViewController
using Swift.
From my rese
You can use protocol to pass data between view controllers
protocol YourFirstViewControllerDelegate: class {
func onButtonClicked(yourString: [String])
}
For passing data from first view controller to second in your Main view Controller when you want to show your first view controller:
you should set main view controller to your view controller delegate, yourFirstViewController.setDlegate(self)
In FirstViewController you should raise an event to main with onButtonClicked([String])
In onButtonClicked([String]) you can call secondViewController and pass your array with onSecondViewController([String])
class MainViewController: UIViewController,YourFirstViewControllerDelegate{
var yourString = [String]()
weak var vcFirst: FirstViewController?
weak var vcSecond: SecondViewController?
func onFirstViewController(){
if (self.vcFirst == nil){
self.vcFirst = self.storyboard?.instantiateViewController(withIdentifier: "FirstViewController") as? FirstViewController
self.vcFirst!.view.translatesAutoresizingMaskIntoConstraints = false
self.vcFirst?.setDelegate(youeFirstViewControllerDelegate: self)
}
self.setActiveController(viewController: self.vcFirst)
}
func onSecondViewController(yourString:[String]){
if (self.Second == nil){
self.Second = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
self.vcSecond!.view.translatesAutoresizingMaskIntoConstraints = false
self.vcSecond.setArray(yourArray: self.yourArray)
}
self.setActiveController(viewController: self.vcSecond)
}
....// your view controller method
func onButtonClicked(yourString: [String]){
self.yourString = yourString
onSecondViewController(yourString:self.yourString)
}
In your First view controller
class FirstViewController: UIViewController{
weak var yourFirstViewControllerDelegate: YourFirstViewControllerDelegate?
var yourString = ["test1","test2"]
// all your overide method should be here
func setDelegate(yourFirstViewControllerDelegate: YourFirstViewControllerDelegate){
self.yourFirstViewControllerDelegate = yourFirstViewControllerDelegate
}
func onButtonClicked(){
self.yourFirstViewControllerDelegate.onButtonClicked(self.yourString)
}
In your second view controller
class SecondViewController: UIViewController{
var yourString = [String]
// all your overide method should be here and you can use your [String]
func setArray(yourString:[String]){
self.yourString = yourString
}
}
I have not Mac OS to check my code now please just read this code not copy, I'll edit this code tomorrow