ios - 通过 Root View Controller 传递对象

标签 ios swift swift2 segue

我有一个以编程方式创建的 rightBarButtonItem,我想触发导航 Controller 的模式转场。导航 Controller 是我的编辑 View Controller 场景的“ Root View Controller ”。

这是一个 example of what I'm talking about ,不同之处在于按钮是在 Storyboard 中创建的,因此您可以控制并从 Storyboard 中的按钮中拖动 segue。这就是我所说的结构

HomeVC --(modal)--> Navigation Controller --(root view)--> EditVC

我无法在 Storyboard中插入 rightBarButtonItem,因此我必须以编程方式创建一个 made the segue to the Navigation Controller following this answer

我在这里的目的是展示一个模态屏幕来编辑一个对象,所以我需要通过导航 Controller 将该对象从我的 HomeVC 传递到我的 EditVC 中。第一个链接中的示例是创建一个对象,因此不需要传递任何内容。

这就是我现在的位置。我的 HomeVC(简化名称以便于理解)有一个导航栏,其中包含一个以编程方式创建的 rightBarButtonItem,其选择器调用一个函数:

func editButtonPressed() {
    // doesn't call prepareForSegue unless I prepend super.
    super.performSegueWithIdentifier("ShowEdit", sender: self)     
}

我的问题在于我的 prepareForSegue 函数:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    print("this one prints")
    if segue.identifier == "ShowEdit" {
        print("this one prints")
        // prints out the UINavigationController, not the EditVC
        print("segue: \(segue.destinationViewController)")
        if let editViewController = segue.destinationViewController as? EditViewController {
            // THIS IS WHAT I WANT TO ACCOMPLISH
            editViewController.selectedObject = selectedObject
            print("DOES NOT PRINT")
        } else {
            print("this one prints")
        }
    }

因此,如果您明白我的意思,我想将对象从 HomeVC 传递到 EditVC,但我的 segue 当前转到 Navigation Root View Controller 。如何通过导航 Controller 将其传递给 EditVC?

我想为 Nav Controller 创建一个 Controller ,所以它将是 myNavVC.selectedObject == selectedObject,然后在 myNavVC 的 prepareForSegue 中通过 EditVC.selectedObject == selectedObject 传递它,但是由于标识符是 Root View ,我将使用什么作为标识符?

最佳答案

在 Objective-C 中演示它:

UINavigationController *navigationController = (UINavigationController*)segue.destinationViewController;

EditViewController *editViewController = (EditViewController *)[[navigationController viewControllers] firstObject];

editViewController.selectedObject = selectedObject;

Swift 中的演示:

if let navigationController = segue.destinationViewController as? UINavigationController {
    if let editViewController = navigationController.viewControllers.first as? EditViewController {
                editViewController.selectedObject = selectedObject
    }
}

关于ios - 通过 Root View Controller 传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38152970/

相关文章:

ios - 在 iOS 通用应用程序中启动屏幕 Storyboard约束

ios - NSURLSessionConfiguration HTTPAdditionalHeaders 未设置

iphone - 如何覆盖 ABNewPersonViewController 中的 "Done"按钮

ios - 我可以在 iOS 中以编程方式设置对象属性吗?

ios - Xcode 7 - 无法调用 AudioFileStreamOpen

ios - 如何检测在swift 2中单击了哪个表格单元格

iphone - 我需要一些关于@2x UIImageViews 的信息

ios - CollectionView失去对数据模型的引用

swift - 在 Vapor 中使用第三方 OAuth API

swift - 如何快速从 CoreData 获取关系?