jaykaydev
jaykaydev

Reputation: 141

Create UITableView with multiple Custom Cells in Swift

What is the best current way to create an UITableView with multiples Custom Cell with the storyboard and the tableView methods?

For now, I get correctly my JSON response split into 3 arrays then I want to use it to update my tableView with 3 different custom cells.

class MainViewController: UIViewController {

    // MARK: - Properties
    var starters = [Starter]()
    var dishes = [Dish]()
    var deserts = [Desert]()

    // MARK: - Outlets
    @IBOutlet weak var foodTableView: UITableView!

    // MARK: - Functions
    func updatDisplay() {
        ApiHelper.getFoods { starters, dishes, deserts in
            self.starters = starters
            self.dishes = dishes
            self.deserts = deserts
            self.foodTableView.reloadData()
        }
    }

    // MARK: - View Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        updatDisplay()
    }
}

extension MainViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StarterCell", for: indexPath)

        return cell

    }
}

Upvotes: 2

Views: 5626

Answers (1)

sundance
sundance

Reputation: 3020

Assuming that you have the three sections "starters", "dishes" and "deserts" you can display the cells like this:

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

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

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "Starters"
    }
    else if section == 1 {
        return "Dishes"
    }
    else {
        return "Deserts"
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        return tableView.dequeueReusableCell(withIdentifier: "StarterCell", for: indexPath)
    }
    else if indexPath.section == 1 {
        return tableView.dequeueReusableCell(withIdentifier: "DishesCell", for: indexPath)
    }
    else {
        return tableView.dequeueReusableCell(withIdentifier: "DesertsCell", for: indexPath)
    }
}

Upvotes: 6

Related Questions