David West David West - 25 days ago 7
iOS Question

TableView with multiple prototype cells

I had a simple question regarding a table view with 3 different kinds of prototype cells. The first two occur just once while the third occurs 4 times. Now what I'm confused about is how to specify in my cellforRowatindexpath which cell prototype to use for which row. So, I want something like for row 0, use prototype 1, for row 1, use prototype 2, for rows 3,4,5 and 6 use prototype 3. What's the best way to do this? Do i give each prototype an identifier and then use dequeueReusableCellWithIdentifier:CellIdentifier ?
Can you'll provide some sample code?

EDIT:

Still not working. This is the code I have at the moment. ( I only have one case for the switch statment because I just want to test and see if the cell is being generated in the first row or not, but currently table view is blank)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch(indexPath.row)
{
case 0: {static NSString *CellIdentifier = @"ACell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:@"ACell"];
if(cell==nil) {
cell=[[UITableViewCell alloc]
initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ACell"];

}
return cell;
break;
}
}
}


Acell is my identifier for a cell prototype that I created. I

Answer

If you are using three prototype then use three identifiers. Because only one identifier will cause problem. And you will get wrong result. So code like this.

if(indexPath.row==0){
 // Create first cell
}

if(indexPath.row==1){
 // Create second cell
}

else{
 // Create all others
}

You can use switch case also here for best performance.

Comments