从另一个ViewController进行Performsegue不起作用

时间:2018-08-28 05:18:43

标签: storyboard singleton segue viewcontroller swift4.2

到目前为止,我一直在使用Objective-C,并决定从现在开始迅速开发。

我不知道为什么这个简单的代码不起作用。

我有两个viewController作为Superview的容器视图,一个叫做'sideViewController',另一个叫做'dashViewController'。

我从dashViewController到另一个名为'nextViewController'的viewController的标识符为'Appointment'的segue

如果我尝试在dashViewController.swift中执行举报,则工作正常。

但是,如果我尝试在'sideViewController'中使用它,为什么它不起作用?

@IBAction public func buttonTapped(_ sender: Any) {
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "dashboardViewController")
    vc.performSegue(withIdentifier: "Appointment", sender: self) //nothing happens
}

在目标C中,我可以对dashViewController使用单例,如下所示

[[MainViewController sharedViewController] performSegueWithIdentifier:@"Appointment" sender:nil];

但是很快,以下代码不起作用

DashboardViewController.sharedInstance.performSegue(withIdentifier: "Appointment", sender: nil)

我已经为此苦苦挣扎了两天了。

请帮助我。

谢谢

1 个答案:

答案 0 :(得分:0)

buttonTapped()函数中,您正在创建“ dashboardViewController”的 new 实例,然后尝试执行segue ...但是您没有不会将新的VC或其视图添加到层​​次结构中,因此即使要执行segue ,也没什么可看的。

您要使用的是协议/委托模式。

创建一个协议,以便在“ sideViewController”中单击按钮可以告诉其委托(“主”视图控制器)告诉“ dashboardViewController”的现有实例来执行segue。

协议和委托在Swift中的功能与Obj-C中的相同...只是语法不同。