UITableView的自定義cell

自定義UITableViewCell大體有兩類方法:佈局

<一>使用nib spa

一、xib中指定cell的Class爲自定義cell類型(注意不是設置File's Owner的class)資源

二、調用 tableView 的 registerNib:forCellReuseIdentifier:方法向數據源註冊cell 頁面佈局

    [_tableView registerNib:[UINib nibWithNibName:@"xxxxxCell" bundle:nil] forCellReuseIdentifier:kCellIdentify]; it

 

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

    xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];class

 

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

 

<二>不使用nib 方法

一、重寫自定義cell的initWithStyle:withReuseableCellIdentifier:方法進行佈局 im

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

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

    if (self)

    {

        // cell頁面佈局

        [self setupView]; 

    } 

    return self; 

 

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

    [_tableView registerClass:[xxxxxCell class] forCellReuseIdentifier:kCellIdentify];

 

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

 

    xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];

 

四、獲取cell時若無可重用cell,將調用cell中的initWithStyle:withReuseableCellIdentifier:方法建立新的cell

 

 

另外要注意的:

一、dequeueReuseableCellWithIdentifier:與dequeueReuseableCellWithIdentifier:forIndexPath:的區別:

前者沒必要向tableView註冊cell的Identifier,但須要判斷獲取的cell是否爲nil;

後者則必須向table註冊cell,可省略判斷獲取的cell是否爲空,由於無可複用cell時runtime將使用註冊時提供的資源去新建一個cell並返回

 

二、自定義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可省略空值判斷的步驟。

相關文章
相關標籤/搜索