Swift : prepareForSegue with navigation controller

后端 未结 8 846
情书的邮戳
情书的邮戳 2020-12-12 17:46

I am developing an iOS application in Swift.

I want to send data from a view to an other one, using the prepareForSegue function.

However, my target view is

8条回答
  •  抹茶落季
    2020-12-12 18:38

    In Swift 5

    If you must not only segue from a SourceViewController to a DestinationViewController embedded in a UINavigationController, but also to a new Storyboard also, then do the following...

    1. Place a "Storyboard Reference" object from your Object Library next to your source ViewController in Interface Builder, and then drag a segue to it (from a button on the SourceViewController view, for instance). Name the segue identifier "ToOtherStoryboard", for example.

    2. Go to NavigationViewController and give it a Storyboard ID using the Identity Inspector. "DestinationNavVC" would do.

    3. Click the Storyboard Reference icon you created in step 1, and in its attribute inspector's 'Referenced ID' field, enter the Storyboard ID you wrote for the UINavigationController in step 2. This creates the segue from source to the DestinationViewController no matter what you write in source file of the source ViewController. This is because seguing to a NaviationController will automatically show the root ViewController (the first one) of the UINavigationController.

    4. (OPTIONAL) If you need to attach data along with your segue and send it to properties within the DestinationViewController, you would write the following code inside a Prepare-For-Segue method in your SourceViewController file:

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if segue.identifier == "ToOtherStoryboard" {
              let destinationNavVC = segue.destination as! UINavigationController
              let destinationVC = destinationNavVC.topController as!     DestinationViewController
      
              destinationVC.name = nameTextField.text // for example
              destinationVC.occupation = occupationTextField.text
          }
      }
      

      You do not NEED to have a PrepareForSegue if you're simply trying to move from one ViewController to another, the methods above will work (w/o step 3)

    5. In your IBAction Outlet method for your button you used to initiate the segue, you would write:

      performSegue(withIdentifer: "ToOtherStoryboard", sender: self)
      

提交回复
热议问题