自定義UITableViewCell(registerNib: 與 registerClass: 的區別)

自定義UITableViewCell大致有兩類方法:
<一>使用nib 
1、xib中指定cell的Class爲自定義cell類型(注意不是設置File's Owner的class) 


21_231933_da3b05024b15a20.png
 

2、調用 tableView 的 registerNib:forCellReuseIdentifier:方法向數據源註冊cell 

複製代碼
  1. [_tableView registerNib:[UINib nibWithNibName:@"xxxxxCell" bundle:nil] forCellReuseIdentifier:kCellIdentify]; 



3、在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier:forIndexPath:獲取重用的cell,若無重用的cell,將自動使用所提供的nib文件創建cell並返回(若使用舊式dequeueReuseableCellWithIdentifier:方法需要判斷返回是否爲空而進行新建)

複製代碼
  1. xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath]; 



4、獲取cell時若無可重用cell,將創建新的cell並調用其中的awakeFromNib方法,可通過重寫這個方法添加更多頁面內容


<二>不使用nib 
1、重寫自定義cell的initWithStyle:withReuseableCellIdentifier:方法進行佈局 

複製代碼
  1. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 

  2. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 

  3. if (self) 

  4. // cell頁面佈局 

  5. [self setupView]; 

  6. return self; 



2、爲tableView註冊cell,使用registerClass:forCellReuseIdentifier:方法註冊(注意是Class) 

複製代碼
  1. [_tableView registerClass:[xxxxxCell class] forCellReuseIdentifier:kCellIdentify]; 



3、在cellForRowAtIndexPath中使用dequeueReuseableCellWithIdentifier:forIndexPath:獲取重用的cell,若無重用的cell,將自動使用所提供的class類創建cell並返回 

複製代碼
  1. 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可省略空值判斷的步驟。

複製代碼
  1. [/code][code]


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