標籤:style blog http io ar color os 使用 sp
使用UINib類靜態方法nibWithNibName:bundle:載入xib(nib)檔案,第一個參數無須加檔案尾碼。若加尾碼,則程式報錯;第二個參數為空白時,程式從mainBundle指向的路徑中搜尋檔案。
正確的寫法:
UINib *storyCellNib = [UINib nibWithNibName:@"StoryCell" bundle:nil];
[self.tableView registerNib:storyCellNib forCellReuseIdentifier:STORY_CELL];
錯誤的寫法:
UINib *storyCellNib = [UINib nibWithNibName:@"StoryCell.xib" bundle:nil]; // 改成StoryCell.nib報相同的錯誤
[self.tableView registerNib:storyCellNib forCellReuseIdentifier:STORY_CELL];
報錯資訊:
*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException‘, reason: ‘Could not load NIB in bundle: ‘NSBundle </Users/michael/Library/Developer/CoreSimulator/Devices/7400CB88-E5F3-4FB5-8A84-FBF2B7AC3134/data/Containers/Bundle/Application/2193EB85-C6B4-4A12-8753-02AEC798B15F/zhihudaily.app> (loaded)‘ with name ‘StoryCell.nib‘‘
在Xcode 6中,如果xib檔案只定義了一個視圖,則不指定File‘s Owner,也指定Custom Class的Class,只指定了Indentifer,使用上面的載入方式也可正常工作。不過,此視圖無法添加新的輸出介面(IBOutlet)和動作響應(IBAction)。而且,當xib檔案中存在多個不同視圖時,上述載入方式將報如下錯誤:
*** Assertion failure in -[UITableView _dequeueReusableViewOfType:withIdentifier:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:6090
2014-11-24 23:21:18.322 zhihudaily[13323:1498086] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException‘, reason: ‘invalid nib registered for identifier (StoryCell) - nib must contain exactly one top level object which must be a UITableViewCell instance‘
所以,最好為自訂視圖指定Custom Class或File‘w Owner。
結論:當使用nibWithNibName:bundle:方法載入xib檔案時,此檔案只允許定義一個頂級的視圖,若定義多個頂級視圖,則產生異常。
iOS 8 & Xcode 6:UINib載入xib檔案問題