自訂UITableViewCell(registerNib: 與 registerClass: 的區別),定金與訂金的區別
自訂UITableViewCell大致有兩類方法: <一>使用nib 1、xib中指定cell的Class為自訂cell類型(注意不是設定File's Owner的class)
2、調用 tableView 的 registerNib:forCellReuseIdentifier:方法向資料來源註冊cell
[_tableView registerNib:[UINib nibWithNibName:@"xxxxxCell" bundle:nil] forCellReuseIdentifier:kCellIdentify];
3、在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier:forIndexPath:擷取重用的cell,若無重用的cell,將自動使用所提供的nib檔案建立cell並返回(若使用舊式dequeueReuseableCellWithIdentifier:方法需要判斷返回是否為空白而進行建立)
xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
4、擷取cell時若無可重用cell,將建立新的cell並調用其中的awakeFromNib方法,可通過重寫這個方法添加更多頁面內容
<二>不使用nib 1、重寫自訂cell的initWithStyle:withReuseableCellIdentifier:方法進行布局
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { // cell頁面配置 [self setupView]; } return self;}
2、為tableView註冊cell,使用registerClass:forCellReuseIdentifier:方法註冊(注意是Class)
[_tableView registerClass:[xxxxxCell class] forCellReuseIdentifier:kCellIdentify];
3、在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier:forIndexPath:擷取重用的cell,若無重用的cell,將自動使用所提供的class類建立cell並返回
xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
4、擷取cell時若無可重用cell,將調用cell中的initWithStyle:withReuseableCellIdentifier:方法建立新的cell
另外要注意的:1、dequeueReuseableCellWithIdentifier:與dequeueReuseableCellWithIdentifier:forIndexPath:的區別:前者不必向tableView註冊cell的Identifier,但需要判斷擷取的cell是否為nil;後者則必須向table註冊cell,可省略判斷擷取的cell是否為空白,因為無可複用cell時runtime將使用註冊時提供的資源去建立一個cell並返回
2、自訂cell時,記得將其他內容加到self.contentView 上,而不是直接添加到 cell 本身上
總結:1.自訂cell時,若使用nib,使用 registerNib: 註冊,dequeue時會調用 cell 的 -(void)awakeFromNib不使用nib,使用 registerClass: 註冊, dequeue時會調用 cell 的 - (id)initWithStyle:withReuseableCellIdentifier:2.需不需要註冊?使用dequeueReuseableCellWithIdentifier:可不註冊,但是必須對擷取回來的cell進行判斷是否為空白,若空則手動建立新的cell;使用dequeueReuseableCellWithIdentifier:forIndexPath:必須註冊,但返回的cell可省略空值判斷的步驟。