Sections in UITableView with Custom Cells

4.4k Views Asked by At

I have the following code thus far.

var someData = [SomeData]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1

        return cell 

    } else {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? Cell2
        let someData = [indexPath.row]
        //Set up labels etc.


        return cell!
    }
}

I need Cell1 which is a static cell and will always remain at indexPath 0 to be in a section called "Section1" for example & all of the Cell2's to be in a section called "Section2"

Other DataSource & Delegate Methods;

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 1
    } else {
        return someData.count
    }
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "Section1" }
    else {
        return "Section2"
    }
}

This returns me everything I need for the first section, however, when it comes to the second section (because of the code inside cellForRowAtIndex somewhere) section 2 contains Cell2 at indexPath 0.

Any help greatly appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

Root cause:

In cellForRowAtIndexPath check for indexPath.section instead of indexPath.row

Fix:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1

        return cell 

    } else {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? Cell2
        let someData = [indexPath.row]
        //Set up labels etc.


        return cell!
    }
}