在学习iOS开发的时候,学习使用xib自定义View,然后在storyboard中使用,虽然直接编译运行没有问题,但是在Interface Builder(简称IB)中预览的时候,一直会报一个Failed to render and update auto layout status for ViewController: The agent threw an exception的问题,并且也无法预览。

xcode显示的错误信息
经过一番搜索之后,在
stackoverflow上看到下面的提问:Failed to render instance of ClassName: The agent threw an exception loading nib in bundle
其中高赞回答如下:

WX20190111-105016.png
我的加载
xib方法如下:
guard let result = Bundle.main.loadNibNamed("TestView", owner: self, options: nil) as? [UIView] else {
fatalError("init failed")
}
Bundle.main可以获取我们的app的main bundle,但是IB会获取到nil,所以导致无法加载xib,并报上面的错误信息。
根据回答中的方法将加载xib的代码改动成下面的代码:
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "TestView", bundle: bundle)
guard let result = nib.instantiate(withOwner: self, options: nil) as? [UIView] else {
fatalError("init failed")
}
改动之后就可以在IB中预览我们自定义的view了。
如过storyboard还是报错误,可以重启xcode后,再打开storyboard进行预览。