How to Group UITableView cells

1.8k views Asked by At

I am trying to make a tableview with cells split into sections with uitableview grouped. I have looked around and found out how to split it into sections though I am stuck on making them appear in groups like they should instead of three groups with all of the cells in each which is what I have at the moment this is what I have got so far after doing a bit of research:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    if ([indexPath section] == 0) {
        if (indexPath.row == 0) {
            cell = cell1;
        } else if (indexPath.row == 1) {
            cell = cell2;
        } else if (indexPath.row == 2) {
            cell = cell3;
        }   
    }
    if ([indexPath section] == 1) {
        if (indexPath.row == 0) {
            cell = cell4;
        } else if (indexPath.row == 1) {
            cell = cell5;
        } else if (indexPath.row == 2) {
            cell = cell6;
        }
    }
    if ([indexPath section] == 2) {
        if (indexPath.row == 0) {
            cell = cell7;
        }
    }
    return cell;
}

Though when I run and go to this view the application crashes and in the nslog box it comes up with this error:

*** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableView.m:5471

Thanks in advance

1

There are 1 answers

1
cutsoy On BEST ANSWER

The row indexes start at zero for each new section.

For example:

if ([indexPath section] == 2) {
    if (indexPath.row == 3) {

Should be:

if ([indexPath section] == 2) {
    if (indexPath.row == 0) {

Furthermore, section indexes also start at zero so you probably want to decrement each index in your if statements.