自訂UITableViewCell(registerNib: 與 registerClass: 的區別),定金與訂金的區別

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.