Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple UITableViewCell Classes in One UITableView?

I am putting together a TableView and I need to have multiple cell classes used in the same table.

So for example how would I use more than one cell class in my cellForRowAtIndexPath method?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...

    return cell;
}

I know I could simply replace UITableViewCell with my custom class and use if statements to adjust the class depending on the index, but isn't that a bit messy, what would be a reasonable, and possibly the most intelligent way of doing this?

like image 756
Josh Kahane Avatar asked Jul 25 '12 21:07

Josh Kahane


1 Answers

Sure can. Just create new instances of your custom cells and give them a new CellId.

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   if (condition1)
    {
        static NSString *CellIdentifier1 = @"Cell1";
        UITableViewCell *cell = 
         [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

        // TODO: if cell is null, create new cell of desired type.  
        // This is where you    create your custom cell that is 
        // derived form UITableViewCell.
    }
    else
    {
        static NSString *CellIdentifier2 = @"Cell2";
        UITableViewCell *cell = 
         [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

        //TODO: if cell is null, create new cell of desired type

    }
    // Configure the cell...

    return cell;
}
like image 68
Brian Avatar answered Sep 19 '22 11:09

Brian