Swift : prepareForSegue with navigation controller

2019-01-21 10:24发布

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 preceded by a navigation controller, so it doesn't work.

How can I do this please ?

5条回答
Rolldiameter
2楼-- · 2019-01-21 10:47

Let's say you want to send data from the SendViewController to the ReceiveViewController :

  1. Add this to the SendViewController

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "segueShowNavigation"{
        var DestViewController = segue.destinationViewController as! UINavigationController
        let targetController = DestViewController.topViewController as! ReceiveViewController
        targetController.data = "hello from ReceiveVC !"
    }}
    
  2. Edit the identifier segue to "showNavigationController"

screenshot

  1. In your ReceiveViewController add

this

var data : String = ""

override func viewDidLoad() {
    super.viewDidLoad()
    println("data from ReceiveViewController is \(data)")
}

Of course you can send any other type of data (int, Bool, JSON ...)

查看更多
狗以群分
3楼-- · 2019-01-21 10:50

A one liner in Swift 3:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let vc = segue.destination.childViewControllers[0] as? FooController {
    vc.variable = localvariable
  }
}
查看更多
走好不送
4楼-- · 2019-01-21 10:51

In prepareForSegue access the target navigation controller, and then its top:

let destinationNavigationController = segue.destination as! UINavigationController
let targetController = destinationNavigationController.topViewController

From the target controller you can access its view and pass data.

In old - now obsolete - versions of Swift and UIKit the code was slightly different:

let destinationNavigationController = segue.destinationViewController as UINavigationController
let targetController = destinationNavigationController.topViewController
查看更多
叼着烟拽天下
5楼-- · 2019-01-21 11:03

Here is the answer for Swift 3:

let svc = segue.destination as? UINavigationController

let controller: MyController = svc?.topViewController as! MyController
controller.myProperty = "Hi there"
查看更多
The star\"
6楼-- · 2019-01-21 11:06

Complete answer using optional binding and Swift 3 & 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let navigationVC = segue.destination as? UINavigationController, let myViewController = navigationVC.topViewController as? MyViewControllerClass {
        myViewController.yourProperty = myProperty
    }
}
查看更多
登录 后发表回答