Search code examples
iphoneiosuitableviewcell

Load cell selectively in TableView


I need to return cell in tableView:cellForRowAtIndexPath: only when some condition is true,for example:

if (condition == true)
return nil;
else
return cell;

Returning nil gives me an error.


Solution

  • You'll need to do a little more to conditionally have a cell in a UITableView.

    Let's assume you have 3 cells, and the first one is conditional. The first thing you need to do make your table have either 2 or 3 cells based on this condition:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        if(condition) {
            return 3;
        } else {
            return 2;
        }
    }
    

    Next you can return the actual cell.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        if(condition) {
            if(indexPath.row == 0) {
                //create and return conditional cell
            } else {
                //create and return normal cell
            }
        } else {
            //create and return normal cell
        }
    }
    

    And voila!

    PS: (This is assuming everything is done in a single section. If you need to break that out into multiple sections we can get into that as well).