使用storyBoard方式的UITableView注意事項
storyboard在可視化設(shè)計tableview和tableview的cell的時候非常方便.但是有些人早期可能是從手寫代碼控件過來的,所以這里有一些需要注意的地方.
1. 不能使用registerClass
2. 無需判斷dequeueReusableCellWithIdentifier forIndexPath返回空cell的情況,因為一定會返回非空,并且子類化后的cell不要寫initWithStyle了.
3. cell被重用如何提前知道? 重寫cell的prepareForReuse
----------分割線,后面是具體解釋---------------------------
1. 不能使用registerClass
當(dāng)我們在storyboard方式使用UITableView時候, UITableViewCell不能使用registerClass注冊.
通常在ios6中使用UITableView時候手寫代碼方式,會在viewDidLoad用如下方式注冊重用標(biāo)識.
[self.tableView registerClass:[RecipeBookCell class] forCellReuseIdentifier:@"RecipeCell"];
因為這種方式是給純手工方式使用的. 當(dāng)你使用這個registerClass注冊之后,在storyboard中畫的Dynamic Prototypes就不再生效了.

-
(void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //注意當(dāng)在storyboard中使用這里不能注冊,也無需注冊,storyboard會自動注冊//[self.tableView registerClass:[RecipeBookCell class] forCellReuseIdentifier:@"RecipeCell"];}
復(fù)制代碼
2. 無需判斷dequeueReusableCellWithIdentifier forIndexPath返回空cell的情況,因為一定會返回非空,并且子類化后的cell不要寫initWithStyle了.
另一個需要注意的地方是,在手寫代碼的方式中,通常會判斷 tableView dequeueReusableCellWithIdentifier forIndexPath返回的cell是否為空,如果為空則調(diào)用alloc和initWithStyle. (也就是如果前面使用了registerClass,則需要這個判斷)
而在使用了storyboard的Dynamic Prototypes之后,這里永遠(yuǎn)都不會調(diào)用了.因為dequeueReusableCellWithIdentifier forIndexPath從來不會返回等于nil的cell給你.
同時這也就表示,你的UITableViewCell子類化之后initWithStyle不會被調(diào)用,你也就不要費心在里面寫代碼了.
注: 使用storyboard之后, tableView dequeueReusableCellWithIdentifier和tableView dequeueReusableCellWithIdentifier forIndexPath都不會返回空的cell給你了.所以后面的判斷都不用寫了.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *simpleTableIdentifier = @"RecipeCell"; RecipeBookCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath]; if (cell == nil) { //NSLog(@"如果不用registerClass則每次都不會走這里"); //cell = [[RecipeBookCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:simpleTableIdentifier]; } //這里是在storyboard中畫的控件,在頭文件中關(guān)聯(lián)即可,無需在cell的init方法中初始化,直接用就行 cell.nameLabel.text = [tableData objectAtIndex:indexPath.row]; cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]]; cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row]; return cell;}
復(fù)制代碼
3. cell被重用如何提前知道? 重寫cell的prepareForReuse
官方頭文件中有說明.當(dāng)前已經(jīng)被分配的cell如果被重用了(通常是滾動出屏幕外了),會調(diào)用cell的prepareForReuse通知cell.
注意這里重寫方法的時候,注意一定要調(diào)用父類方法[super prepareForReuse] .
這個在使用cell作為網(wǎng)絡(luò)訪問的代理容器時尤其要注意,需要在這里通知取消掉前一次網(wǎng)絡(luò)請求.不要再給這個cell發(fā)數(shù)據(jù)了.

// if the cell is reusable (has a reuse identifier), this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:. If you override, you MUST call super.- (void)prepareForReuse{ [super prepareForReuse]; NSLog(@"prepareForReuse: %@",_nameLabel.text);}
