Search code examples
swiftuitableviewsections

How to populate UITableView with 2 sections


My issue is with the NumberOfRowsInSection that should read two values.

let sections = ["Apples", "Oranges"]
override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }



override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


//Option A)
        if apples.count & oranges.count != 0 {
           return apples.count & oranges.count
        } else {
            return 0
        }

//Option B)

        if sections[0] == "Apples" {
            return apples.count
        }

        if sections[1] == "Oranges"{
            return oranges.count
        }
        return 0
    }

None of the options work, crashing because it doesn't get the amount of things of one of each other... on the CellForRowAt.

Plus somebody knows how to get the title of those sections as well?


Solution

  • numberOfRows will be called for each section so you need to return the correct value based on the current section being queried:

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? apples.count : oranges.count
    }
    

    You need a similar pattern in cellForRowAt and all of the other data source/delegate methods:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", indexPath: indexPath
        if indexPath.section == 0 {
            cell.titleLabel.text = apples[indexPath.row]
        } else {
            cell.titleLabel.text = oranges[indexPath.row]
        }
    
        return cell
    }
    

    This is simplified and makes lots of assumptions but it gives you the right idea.

    For the headers, you need:

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
         return sections[section]
    }
    

    This answer also assumes you just have the two sections based on two array variables. This is far from ideal. You really should have a single data structure with all of the proper structure. Then no assumptions need to be made. You can add more sections and rows and not have to change any table view code.