storyboard中使用xib自定义的view,在Interface Builder中会报Failed to render and update auto layout status

在学习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可以获取我们的appmain 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进行预览。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容