【问题标题】:Swift Segue programmatically以编程方式 Swift Segue
【发布时间】:2015-08-20 10:28:50
【问题描述】:

我有一个视图控制器,它有一个带有两个按钮的 UISegmentControl。我加载这个视图,当 SegmentValue 发生变化时,我会在视图中添加一个视图控制器。

这是主视图控制器

在我定义控制器的类中

var tabNavigation: UISegmentedControl!
let viewController1:ViewController1 = ViewController1()
let viewController2:ViewController2 = ViewController2()

// 创建段控件

self.tabNavigation = UISegmentedControl(items: ["v1", "v2"])
self.tabNavigation.selectedSegmentIndex = 0
self.tabNavigation.frame = CGRectMake(60, 250, 130, 25)
self.tabNavigation.addTarget(self, action: "segmentedValueChanged", forControlEvents: .ValueChanged)
self.navigationItem.titleView = self.tabNavigation

// set first view
self.addChildViewController(viewController1)
self.view.addSubview(viewController1.view)

// 段改变了

func segmentedValueChanged() {
    if (self.tabNavigation.selectedSegmentIndex == 0) {
        self.addChildViewController(viewController1)
        self.view.addSubview(viewController1.view)
    } else {
        self.addChildViewController(viewController2)
        self.view.addSubview(viewController2.view)

在故事板中,我有一个从 MainViewController 到 ViewController3 的 segue

现在在 ViewController1 中,我正在尝试创建一个从 ViewController1 到 ViewController3 的 segue(应该是以前导航控制器的一部分,因此请使用后退按钮滑动)。但是由于 ViewController1 完全由代码制成,因此 segue 不存在而失败。

我的 segue 代码如下,但显然失败了,因为这是 MainViewController 到 ViewController3 的 segue 标识符

performSegueWithIdentifier("loadVC3", sender: nil)

【问题讨论】:

  • 我还应该注意,我尝试在情节提要中添加 ViewController1,只对 ViewController3 进行 segue,但仍然失败并显示“没有标识符的 segue”

标签: ios swift


【解决方案1】:

您正在寻找的是以编程方式初始化 viewController 然后显示它,因为您需要首先设置一个唯一的 Storyboard ID 然后初始化它。像这样:

let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewController3") as! UIViewController

// and then present it modally
presentViewController(viewController, animated: true, completion: nil)

// or push it onto the navigation stack
pushViewController(viewController, animated: true)

【讨论】:

  • 非常好,正是我想要的。谢谢
【解决方案2】:

您不能以编程方式创建转场。看看这个答案:

Creating a segue programmatically

我可能会使用 XIB 来设计您以编程方式创建的所有视图控制器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2017-10-03
    • 2012-03-29
    • 1970-01-01
    相关资源
    最近更新 更多