解決UITableView xib添加到Storyboard出現IB Designables錯誤

之前提過 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加載機制)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章