使用 instantiateViewControllerWithIdentifier 对实例化的 ViewController 进行 Segue

Posted

技术标签:

【中文标题】使用 instantiateViewControllerWithIdentifier 对实例化的 ViewController 进行 Segue【英文标题】:Segue instantiated ViewController with instantiateViewControllerWithIdentifier 【发布时间】:2014-10-14 09:27:07 【问题描述】:

是否可以在使用 instantiateViewControllerWithIdentifier 实例化的 ViewController 的视图中使用 segue?

这是我正在尝试做的一个最小示例(我在更大的项目中需要类似的东西): 在主故事板中,我有一个 rootViewController、一个带有 StoryboardID“secondViewControllerID”的 secondViewController 和一个 thirdViewController。 secondViewController 通过按钮通过 show-Segue 与 thirdViewController 连接。

在 rootViewController 的类中,我实例化了 secondViewController 并将其视图设置为我的 rootViewController 的子视图:

import UIKit

class ViewController: UIViewController 
    override func viewDidLoad() 
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let storyboard = UIStoryboard(name: "Main", bundle: nil);
        var vc = storyboard.instantiateViewControllerWithIdentifier("secondViewControllerID") as UIViewController
        self.view.addSubview(vc.view)
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

当我现在执行程序时,我正确地看到了子视图(secondViewController)。但是现在 segue 不再起作用(当我单击按钮时,我没有到达 thirdViewController)

有人知道为什么吗?

(在我的项目中,不可能只使用没有 instantiateViewControllerWithIdentifier 的 secondViewController,因为 secondViewController 是 pageViewController 的一部分,它通过 instantiateViewControllerWithIdentifier 管理其 viewControllers)

【问题讨论】:

阅读 Apple 文档:developer.apple.com/library/ios/featuredarticles/… 您应该使用导航控制器来处理视图控制器和视图层次结构之间的转换。 【参考方案1】:

您将一个视图控制器的视图添加为另一个视图控制器的子视图。但默认情况下,点击和手势由您的主视图控制器处理,不会传递给辅助 VC - 因此是您的问题。您需要调用一些函数才能使其正常工作。查看 Apple Docs here。

查看“创建自定义容器视图控制器”部分。总之,您需要用self.addChildViewController(vc)vc.didMoveToParentViewController(self) 函数调用来包装您的addSubview 方法调用。

【讨论】:

以上是关于使用 instantiateViewControllerWithIdentifier 对实例化的 ViewController 进行 Segue的主要内容,如果未能解决你的问题,请参考以下文章

Swift:prepareForSegue 和 instantiateViewController 之间的区别

幽灵视图控制器

导航控制器不能正常工作

如何在uitableviewcell swift上使用pushviewcontroller [重复]

回到初始视图控制器

Swift 回到根视图控制器