壹: 寫在前面
在使用UITableView的時(shí)候, 需要面臨兩種重用Cell
方法的選擇, 這就需要了解什么時(shí)候使用什么方法
, 以及兩種方法到底做了什么
.
貳: 區(qū)別
- 兩種方法的的選擇情況
在iOS 6中
dequeueReusableCellWithIdentifier:
被dequeueReusableCellWithIdentifier:forIndexPath:
所取代枝恋。
- 優(yōu)缺點(diǎn)對(duì)比
如此一來(lái)刽虹,
dequeueReusableCellWithIdentifier:forIndexPath:
在表格視圖中創(chuàng)建并添加UITableViewCell
對(duì)象會(huì)變得更為精簡(jiǎn)而流暢国夜。
-
dequeueReusableCellWithIdentifier:forIndexPath:
做了什么
dequeueReusableCellWithIdentifier:forIndexPath:
一定會(huì)返回cell威始,系統(tǒng)在默認(rèn)沒(méi)有cell可復(fù)用的時(shí)候會(huì)自動(dòng)創(chuàng)建一個(gè)新的cell出來(lái)
。
叁: dequeueReusableCellWithIdentifier:forIndexPath:的使用:
- 使用
dequeueReusableCellWithIdentifier:forIndexPath:
的話肤寝,必須和下面的兩個(gè)配套方法配合起來(lái)
使用
// 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);
- 這樣在
tableView:cellForRowAtIndexPath:
方法中就可以省掉下面這些代碼
static NSString *CellIdentifier = @"Cell";
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];}
- 取而代之的是下面這句代碼:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
肆: More:
在tableView:cellForRowAtIndexPath:
中使用dequeueReusableCellWithIdentifier:forIndexPath:
獲取重用的cell当辐,如果沒(méi)有重用的cell,將自動(dòng)使用提供的class類
創(chuàng)建cell并返回
- 純代碼的情況
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
獲取cell時(shí)如果沒(méi)有可重用的cell鲤看,將調(diào)用cell中的initWithStyle:withReuseableCellIdentifier:
方法創(chuàng)建新的cell