Search code examples
swiftuitableviewsections

tableview with 2 sections different design for cells


I need 2 have 2 tables in the same screen(different design of the cells for each table).

I am not sure if I should work with 2 tables in the same view(the scroll gets messed up right now) or have a table with 2 sections and design de cells in each sections differently.

I haven't managed to find any example with a table view with 2 sections and different design of cells in the 2 sections.

Is it possible?

Or should I try to make it work out with 2 different tables?


Solution

  • I haven't managed to find any example with a table view with 2 sections and different design of cells in the 2 sections. Is it possible?

    Yes it is possible :)

    This is where you use the method tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell from the UITableViewDataSource protocol.

    You check which section you are to return a subclass of UITableViewCell for, create an instance, maybe populate it and then you return that.

    So for this to work you'd need.

    • To create a number of subclasses of UITableViewCell with NIB files.
    • For instance in viewDidLoad() you register the NIBs like so:

      tableView.registerNib(UINib(nibName: "Cell1", bundle: nil), forCellReuseIdentifier: "Cell1")
      tableView.registerNib(UINib(nibName: "Cell2", bundle: nil), forCellReuseIdentifier: "Cell2")
      
    • In tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) you check which section is asked for and return the proper subclass like so (with room for improvements :-)):

      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          switch indexPath.section {
          case 0:
              if let cell1 = tableView.dequeueReusableCellWithIdentifier("Cell1") as? Cell1 {
                  //populate your cell here
                  return cell1
              }
          case 1:
              if let cell2 = tableView.dequeueReusableCellWithIdentifier("Cell2") as? Cell2 {
                  //populate your cell here
                  return cell2
              }
          default:
              return UITableViewCell()
          }
          return UITableViewCell()
      }
      

    Hope that helps