techno techno - 1 month ago 7
Swift Question

Pass Array of URLs to another View Controller via Segue

I have a single Window controller and 2 View Controllers.When the user clicks a button I need to open the second View Controller.I clicked and dragged a segue from the first view to the second view from a button.Now when the user clicks the Button the second View Controller opens up

enter image description here

Now I need to pass some data-Array of URLs from the first View Controller to the second.It seems that I need to override some function of the segue to achieve this

I have tried the following code from the answer related to IOS here
How do you pass data between view controllers in Swift?

Since the classes are different for OSX,many classes are undefined

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "YourSegueName") {
//get a reference to the destination view controller
let destinationVC:ViewControllerClass = segue.destinationViewController as! ViewControllerClass

//set properties on the destination view controller
destinationVC.name = viewName
//etc...
}
}


So far I know how to override the segue preparation in OSX.I don't know how to identify the segue and pass the required data to the new ViewController.

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
}


Please advice.

Answer Source

You're nearly there, your code just needs some tweaks for MacOS.

Your prepare for segue method would look like this:

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
  if (segue.identifier?.rawValue == "YourSegueName") {
    //get a reference to the destination view controller
    let destinationVC:MyViewController = segue.destinationController as! MyViewController

    //set properties on the destination view controller
    destinationVC.urls = [] //pass in urls here
  }
}

You can see there are a few adjustments for MacOS, UIStoryboardSegue->NSStoryboardSegue, AnyObject->Any (This should be Any now in iOS too), you'll need the rawValue of the identifier, destination->destinationController.

The ViewControllerClass mentioned in your code refers to a class that you create that subclasses NSViewController. I've created an example called MyViewController, just to show you what it could look like:

class MyViewController: NSViewController {
  var urls:[URL] = [] {
    didSet(newValue) {
      //do something here
    }
  }
  override func viewDidLoad() {
        super.viewDidLoad()
  }
}

In the storyboard to make all of this work, you would need to do a few things:

  1. Give the segue an identifier eg. "YourSegueName"
  2. Give the second view controller a class identifier eg. MyViewController

I recommend you read a tutorial on this, for example, Ray Wenderlich's MacOS View Controllers Tutorial.