Ios 如何正确展开UIViewController
我无法真正理解如何打开这段代码,我尝试了if、guard和强制打开,但当id不存在时,它们都会崩溃。是否可以使其在控制台中显示print(),而不执行任何进一步的代码Ios 如何正确展开UIViewController,ios,swift3,Ios,Swift3,我无法真正理解如何打开这段代码,我尝试了if、guard和强制打开,但当id不存在时,它们都会崩溃。是否可以使其在控制台中显示print(),而不执行任何进一步的代码 guard let historyViewController = self.storyboard?.instantiateViewController(withIdentifier: "historyViewNav") else{ fatalError("No history view controlle
guard let historyViewController = self.storyboard?.instantiateViewController(withIdentifier: "historyViewNav") else{
fatalError("No history view controller found ");
}
historyViewController.modalTransitionStyle = .flipHorizontal
present(historyViewController, animated: true, completion: nil)
我不知道我是否明白你想做什么。此处:fatalError(“未找到历史视图控制器”)代码>如果无法从情节提要初始化控制器,则将导致应用程序崩溃。如果您不希望应用程序崩溃,只需在else
语句中使用print()
。如果您不想在那里发生任何其他事情,您可以在之后返回
:
guard let historyViewController = self.storyboard?.instantiateViewController(withIdentifier: "historyViewNav") else{
print("No history view controller found ");
return;
}
InstanceViewController(带标识符:“historyViewNav”)
不返回nil如果失败,则引发异常。请参见此处:。因此,您的guard
语句没有帮助。不幸的是,我不知道在运行时检查这一点的直接方法,因为NSExceptions并不意味着可以在swift中捕获,如下所述:
但是,我建议查看RSwift库,这样您就不必在代码中使用硬编码字符串作为标识符。如果您将ID放在字段中,则此操作有效:
override func viewDidAppear(_ animated: Bool) {
if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "myTestID") as? UIViewController
{
vc.modalTransitionStyle = .flipHorizontal
present(vc, animated: true, completion: nil)
}else{
print("error")
}
}
在任何情况下,警卫必须通过返回或类似的方式终止。我可以问一个问题吗?为什么不设置ID?由于未捕获的异常“NSInvalidArgumentException”,导致应用程序崩溃-终止,原因:“序列图像板()不包含标识符为“historyViewNav”的视图控制器@AndreyTsarev:您在序列图像板中设置了ID吗?不,我没有。我想检查一下它是否存在。如果它存在,那就去做,如果它不存在,那就去做别的事情。对不起<代码>实例化视图控制器(带标识符:“historyViewNav”)
不返回nil如果失败,则引发异常。因此,您的guard
语句没有帮助。不幸的是,我不知道在运行时直接检查这一点的方法。但是,我建议查看RSwift库,这样您就不必在代码中使用硬编码字符串作为标识符。