UITableView的registerClass forCellReuseIdentifier用法詳解

tableView: cellForRowAtIndexPath:方法中有兩個(gè)獲得重用cell的方法

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]

請(qǐng)問(wèn)他們有什么區(qū)別?

當(dāng)我用 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]的時(shí)候?yàn)槭裁纯倛?bào)錯(cuò)

reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

------解決方案--------------------------------------------------------

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath

NS_AVAILABLE_IOS(6_0); // newer

區(qū)別在這兒

------解決方案--------------------------------------------------------

1 這個(gè)方法在SDK5.0是運(yùn)行不起來(lái)的。

2 如果需要使用這個(gè)方法,你必須使用配套的方法來(lái)一起用,下面兩個(gè)配套方法:

// Beginning in iOS 6, clients can register a nib or class for each cell.

// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.

// Instances returned from the new dequeue method will also be properly sized when they are returned.

- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);

- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

注意看上面的注釋

3 比如你已經(jīng)用NIB做了一個(gè)Cell,或者自定義了一個(gè)Cell。我們?cè)谀銊?chuàng)建UITableView的時(shí)候,就可以順帶

self.tableView.backgroundColor = xxxx;

[self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];

這樣你在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath這個(gè)方法里,你就可以省下這些代碼:

static NSString *CellIdentifier = @"Cell";

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

//設(shè)置你的cell

而只需要

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

這樣就夠了,這下你明白了嗎?

轉(zhuǎn)載自:? http://www.zpluz.com/thread-3504-1-1.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容