tableview with storyboard in xcode5

The identifier in the defined in the cellForRowAtIndexPath method MUST be the same as what is specified in the storyboard’s prototype cells’s indentifier .

This takes me almost half a day to figure out. Otherwise the table will load the data, but all the other config you did in the storyboard will not be valid because the cell return in the cellForRowAtIndexPath is different with the one in storyboard for the reason that they do no share the same identifier.

Have not been developing ios stuff for a long time, really suffers from this today, sigh.

PS:

无需判断dequeueReusableCellWithIdentifier forIndexPath返回空cell的情况,因为一定会返回非空,并且子类化后的cell不要写initWithStyle了.

 

另一个需要注意的地方是,在手写代码的方式中,通常会判断 tableView dequeueReusableCellWithIdentifier forIndexPath返回的cell是否为空,如果为空则调用alloc和initWithStyle. (也就是如果前面使用了registerClass,则需要这个判断)

而在使用了storyboard的Dynamic Prototypes之后,这里永远都不会调用了.因为dequeueReusableCellWithIdentifier forIndexPath从来不会返回等于nil的cell给你.

同时这也就表示,你的UITableViewCell子类化之后initWithStyle不会被调用,你也就不要费心在里面写代码了.

注: 使用storyboard之后, tableView dequeueReusableCellWithIdentifier和tableView dequeueReusableCellWithIdentifier forIndexPath都不会返回空的cell给你了.所以后面的判断都不用写了.

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 static NSString *identifier = @"SongItem";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// if(cell == nil){
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
// }
 cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
 return cell;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s