![](/img/trans.png)
[英]What's the difference between nil and NSBundle in UIStoryboard()?
[英]UIStoryboard: What's the Correct Way to Get the Active Storyboard?
我目前正在疯狂地翻阅所有文档,但还没有完全找到我要找的东西。 我怀疑这是一个真正的 d'oh! 回答。
我只需要在主包中找到活动的故事板,并想知道这样做的最佳方法。
这样我就可以使用[UIStoryboard storyboardWithName:@"XXX" bundle:mainBundle]
来提取正在运行的故事板。
我知道如何通过打开成语来混杂它,但我觉得这是一个......混杂。
这样做的正确方法是什么?
如果您想获取 viewController 的活动情节提要,则有一个情节提要属性。 这就是我解决它的方法,而不是创建一个新实例:
LoginViewController *vc = [navController.storyboard instantiateViewControllerWithIdentifier:@"firstLaunch"];
[navController presentModalViewController:vc animated:YES];
在 Swift 中,你会调用:
let loginViewController = navigationController?.storyboard?.instantiateViewController(withIdentifier: "firstLaunch") as! LoginViewController
navigationController?.present(loginViewController, animated: true, completion: nil)
通过使用对导航控制器和故事板的防护,您也可以更安全。 我用过as!
以保证你得到一个 LoginController。
好的。 正如我上面的评论所示,我找到了(措辞不当的问题)的答案:
我希望能够获得主要(非活动)故事板,因为我没有在每个化身中使用多个故事板。 我正在使用 iPhone 的 1 个故事板和 iPad 的 1 个故事板的标准模型。 我只想以最简洁的方式获取故事板,以便我可以使用它来生成视图控制器。
我在 Stack Overflow 上的这篇文章中找到了答案,并使用以下代码实现了它:
UIStoryboard *st = [UIStoryboard storyboardWithName:[[NSBundle mainBundle].infoDictionary objectForKey:@"UIMainStoryboardFile"] bundle:[NSBundle mainBundle]];
在Swift 中,您将使用以下语法:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
请注意,将nil
传递给bundle
将使调用自动引用您的主包。
如果您在 Storyboard 上的视图控制器中并想直接从那里实例化 Storyboard,您可以这样做:
let storyboard: UIStoryboard? = self.storyboard // call this inside a VC that is on the Storyboard
请注意,在最后一种情况下, self.storyboard
将返回一个可选的Storyboard ( Storyboard?
),因此如果您想使用它,请像这样解开它:
if let storyboard = self.storyboard {
// access storyboard here
}
我刚刚复制粘贴了更新问题上方的代码表单,以便每个人都可以将其视为答案。
UIStoryboard *st = [UIStoryboard storyboardWithName:[[NSBundle mainBundle].infoDictionary objectForKey:@"UIMainStoryboardFile"] bundle:[NSBundle mainBundle]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.