Swift:使用导航控制器prepareForSegue

ced*_*tin 63 uinavigationcontroller ios swift

我正在Swift中开发一个iOS应用程序.

我想使用prepareForSegue函数将视图中的数据发送到另一个视图.

但是,我的目标视图前面是导航控制器,所以它不起作用.

我该怎么办?

Woj*_*wka 125

prepareForSegue访问目标导航控制器,然后它的顶部:

let destinationNavigationController = segue.destination as! UINavigationController
let targetController = destinationNavigationController.topViewController
Run Code Online (Sandbox Code Playgroud)

从目标控制器,您可以访问其视图并传递数据.

在旧的 - 现在已经过时 - 版本的Swift和UIKit中,代码略有不同:

let destinationNavigationController = segue.destinationViewController as UINavigationController
let targetController = destinationNavigationController.topViewController
Run Code Online (Sandbox Code Playgroud)

  • @biggreentree最有可能你需要投`destinationNavigationController.topViewController`到secondViewController`的`类型. (7认同)

mat*_*tyU 27

假设您要将SendViewController中的数据发送到ReceiveViewController:

  1. 将其添加到SendViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segueShowNavigation" {
            if let destVC = segue.destination as? UINavigationController,
                let targetController = destVC.topViewController as? ReceiveViewController {
                targetController.data = "hello from ReceiveVC !"
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将标识符segue编辑为"showNavigationController"

截图

  1. 在你的ReceiveViewController中添加

这个

var data : String = ""

override func viewDidLoad() {
    super.viewDidLoad()
    print("data from ReceiveViewController is \(data)")
}
Run Code Online (Sandbox Code Playgroud)

当然你可以发送任何其他类型的数据(int,Bool,JSON ......)


jas*_*n z 16

使用optional binding和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
    }
}
Run Code Online (Sandbox Code Playgroud)