從 XIB 建立 UITableViewCell 的問題

自己試著使用 XIB 把不同東西切割出來,像是 UITableViewCell

在 UITableView 的 viewDidLoad 裡面建立好相關的參照

- (void)viewDidLoad {
  [super viewDidLoad];

  [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCell"
                                             bundle:[NSBundle mainBundle]]
       forCellReuseIdentifier:cellIdentifier];
}

再建立 cell 時候,大概像這樣使用

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
    // do cell things ...
    return cell;
}

然後執行之後會出錯,大概會看到像這樣的錯誤

*** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:6116
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier MyTableViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

原因是使用 dequeueReusableCellWithIdentifier:forIndexPath: 會去 UITableView 查用把 XIB 裡面要的東西建立起來,這個動作會順便檢查 XIB 裡面的 View 是不是 UITableViewCell,若不是的話會吐 NSInternalInconsistencyException

[閱讀全文]
Tags: iOS XIB UITableView