Adding multiple custom cells in UITableView

后端 未结 2 1107
悲&欢浪女
悲&欢浪女 2021-02-09 00:08

Though this is one of the most asked question but i could not find one comprehensive answer. I need to have custom cells in UITableView. Some containing labels or text fields an

2条回答
  •  终归单人心
    2021-02-09 00:37

    To answer your first question, you may as well return nil as you have no good value to return. If it ever hits this case, an exception will be thrown; as it is now, it's likely to give you an EXC_BAD_ACCESS somewhere inside the framework code.

    To answer your second question, each type of cell should have a unique reuseIdentifier. For example, all the CellA's could have a reuseIdentifier of @"CellA". Then you would reuse them exactly as you would in the case that all the cells were the same: when you need a CellA call [tableView dequeueReusableCellWithIdentifier:@"CellA"], when you need a CellB call [tableView dequeueReusableCellWithIdentifier:@"CellB"], and so on. For example,

        case 0:
            if (indexPath.row == 0) {
                CellA *cell = [tableView dequeueReusableCellWithIdentifier:@"CellA"];
                if (!cell) {
                    cell = [[[CellA alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellA"] autorelease];
                }
                // configure cell
                return cell;
            }
            else if (indexPath.row == 1) {
                CellB *cell = [tableView dequeueReusableCellWithIdentifier:@"CellB"];
                if (!cell) {
                    cell = [[[CellB alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellB"] autorelease];
                }
                // configure cell
                return cell;
            }
            break;
        case 1:
            if (indexPath.row == 0) {
                CellC *cell = [tableView dequeueReusableCellWithIdentifier:@"CellC"];
                if (!cell) {
                    cell = [[[CellC alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellC"] autorelease];
                }
                // configure cell
                return cell;
            }
            break;
    

提交回复
热议问题