UITableView Mix of Static and Dynamic Cells?

After struggled for 1 day, found best solution

Updated for Swift 4

for the case of the question:

  1. Set sections of the tableView to 3

enter image description here

  1. Add a empty tableview cell in the second section which you want to apply the dynamic cells, change identifier of the cell as WiFiTableViewCell

  2. create a new XIB file called WiFiTableViewCell

enter image description here

  1. register the Nib in the function ViewDidLoad in tableViewController

    tableView.register(UINib(nibName: "WiFiTableViewCell", bundle: nil), forCellReuseIdentifier: "WiFiTableViewCell")
    
  2. add the following code to use both dynamic and static cell

    override func numberOfSections(in tableView: UITableView) -> Int 
    {
        return 3
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return self.dataSource.count
            //the datasource of the dynamic section
        }
        return super.tableView(tableView, numberOfRowsInSection: section)
     }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "WiFiTableViewCell") as! WiFiTableViewCell
            return cell
        }
        return super.tableView(tableView, cellForRowAt: indexPath)
    }
    
     override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: NSIndexPath) -> Int {
         if indexPath.section == 1 {
             let newIndexPath = IndexPath(row: 0, section: indexPath.section)
             return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
         }
         return super.tableView(tableView, indentationLevelForRowAt: indexPath)
     }
    
     override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         if indexPath.section == 1 {
             return 44
         }
         return super.tableView(tableView, heightForRowAt: indexPath)
      }
    

Leave a Comment