解决UITableView xib添加到Storyboard出现IB Designables错误

来源:互联网 发布:致远a6协同办公软件 编辑:程序博客网 时间:2024/06/04 08:20

之前提过 Swift下自定义xib添加到Storyboard 的方法。最近有人问说按照文中方法会出现IBDesignables错误,导致在xcode Storyboard中无法显示。

这个应该是我漏讲了。如果你的自定义xib中有UITableView,而且UITableViewCell也是xib,一般这个错误肯定是加载的时候找不到对应的Bundle文件了。

错误如下:
这里写图片描述

IB Designables: Failed to render and update auto layout status for ViewController (BYZ-38-t0r): The agent threw an exception.IB Designables: Failed to update auto layout status: The agent raised a"NSInternalInconsistencyException" exception: Could not load NIB in bundle:'NSBundle </Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Overlays> (loaded)' with name 'MyTableViewCell'

为什么会出现这个错误?

这个就要说到ios xib(Storyborad)加载机制了,但apple把这个Bundle加载机制隐藏的很深,之后我会单独写一篇文章介绍xib(Storyborad)加载机制。这里我简单说下上面的错误是怎么导致的。

上面错误主要因为我们使用的了自定义的MyTableViewCell(Xib),在Storyboard渲染Build的时候,会去读取加载这个MyTableViewCell(Xib)。这个时候我们代码一般是这么写的:

tableView.register(UINib(nibName: "MyTableViewCell", bundle: nil),forCellReuseIdentifier: "MyTableViewCell")

注意这一句:UINib(nibName: "MyTableViewCell", bundle: nil),这个在App运行起来没有问题,因为bundle = nil 则默认使用mainBundle,但是xcode中预览Storyboard的时候,我们App没有运行,所以根据上下文无法找到对应的Bundle,所以导致该Nib无法加载。
所以出现了上面的错误exception: Could not load NIB in bundle


那么如何修改呢?

很简单,既然根据上下文无法找到对应的Bundle,我们告诉它不就行了。改成:

tableView.register(UINib(nibName: "MyTableViewCell",        bundle: Bundle(for: self.classForCoder)),        forCellReuseIdentifier: "MyTableViewCell")

你也可以加载TARGET_INTERFACE_BUILDER来区分下。当然不区分也没关系。

#if TARGET_INTERFACE_BUILDER    tableView.register(UINib(nibName: "MyTableViewCell",        bundle: Bundle(for: self.classForCoder)),        forCellReuseIdentifier: "MyTableViewCell")#else    tableView.register(UINib(nibName: "MyTableViewCell",        bundle: nil),         forCellReuseIdentifier: "MyTableViewCell")#endif

我非常欢迎大家给我提问题(让人民群众监督我学习哈哈哈~~~~, 这不我就得重新理下Nib加载机制)

原创粉丝点击