Search code examples
xcodeios5xcode4.2uitableviewstoryboard

How to re-use some cells from UITableVIewController storyboarding mode Static Cells


I have this UITableViewController which i made a Static Cells using Interface Builder and three added different kind of cells.

The first cell is some kind of details, the last cell allows user input which in-turn gets show the center cell.

enter image description here

I want to reuse the center cell and add new ones as the user enters in the last comment box.

My problem is that, since it's static cells, I can't reuse the center cell alone I think. How can I solve it?


Solution

  • don't use static cells. Static cells are not meant to be reused. With static cells you create a table solely in the xib.

    Create three different prototype cells and give them a different reuse identifier and use them like regular cells.

    Since your table is divided into sections just use the section information of the indexPath to return the correct cell.

    Something like this should work:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 3;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if (section == 1) {
            return _objects.count;
        }
        return 1;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = nil;
        if (indexPath.section == 1) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"SecondCell"];
            // configure the mid cells
            NSDate *object = [_objects objectAtIndex:indexPath.row];
            cell.textLabel.text = [object description];
        }
        if (indexPath.section == 0) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCell"];
            // configure first cell
        }
        else if (indexPath.section == 2) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"ThirdCell"];
            // configure last cell
        }
        return cell;
    }
    

    have a look at the tableFooterView and tableHeaderView property too. Maybe you don't need cells for the first and last item at all.