Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic UITableView

This is rather generic question, I've read many answers, but I'm still wondering how it should be done properly.

When you have a table view that's like the Settings in iOS, where you have a table view cells with many different (in terms of type) cells (some with UISwitche, with UIPickerViews, for more details, with UITextFields, etc) should it be done using a static tableView or a dynamic? And what is the best way to go for achieving something like that?

And I'm asking for cases, where the information should be pulled from a backend like Firebase database for example.

like image 854
Dani Avatar asked Nov 24 '25 07:11

Dani


1 Answers

You should create custom cells in your table view and then you need to detect which type of cell you want to use and after that set cells.

Let´s say that you have three type of cells:

  1. A cell with a Switch (custom)
  2. A cell with a textField (custom)
  3. A regular cell (regular)

In your cellForRowAt you need to detect which kind of cell you want to use. You can either do that by checking the indexPath.row if you have static positions or you can check the data type in your array and set the cell depending on that.

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

    switch indexPath.section {
    case 0:
        let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! SwitchCell
        // set cell values here
        return cell
    case 1:
        let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldCell", for: indexPath) as! TextFieldCell
        // set cell values here
        return cell
    default:
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! UITableViewCell
        // set cell values here
        return cell
    }
}

Here is a good guide of how you can create your custom cells and you can have as many custom cells as you want.

like image 58
Rashwan L Avatar answered Nov 26 '25 23:11

Rashwan L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!