在代码中使用stroyboard中的ViewController

来源:互联网 发布:nginx 图片服务器配置 编辑:程序博客网 时间:2024/05/21 22:22

如果遇到在storyboard中可以正常使用的ViewController,但是用代码中无法正常使用,总是会提示VC中的outlet未初始化,是nil,或者tableview中的cell提示没有注册,那么可以查看本文寻求合理的解决方式

(实训中遇到的问题)

首先持有一个storyboard的对象,假设我们使用的是Main.storyboard

let stb = UIStoryboard.init(name: "Main", bundle: nil)`

中有一个VC叫做MainViewController
那么我们拿到它,使用

let ma = stb.instantiateViewController(withIdentifier: "MainTableViewController")

这个地方一定要注意,这个withIdentifier的参数,填写的是你在storyboard中Storyboard ID属性中填写的内容。

以下是官方API的提示

identifier An identifier string that uniquely identifies the view controller in the storyboard file. You set the identifier for a given view controller in Interface Builder when configuring the storyboard file. This identifier is not a property of the view controller object itself and is used only by the storyboard file to locate the view controllerIf the specified identifier does not exist (or is nil) in the storyboard file, this method raises an exception.

这样就初始化好了。
追究其深层次的原因,我想是代码初始化一个VC和用storyboard初始化一个VC执行的方法是不一样的。用代码的话是执行它的init()方法,而在storyboard中是awakeFromNib()方法。这两个构造方法的不同,是导致上述现象出现的可能原因。

0 0
原创粉丝点击