Search code examples
swiftxcodetableviewcell

Display three reusbale cells in tableview - Swift 5


I have 3 UITableViewCell with XIB files but on my tableview I can't display my three UITableViewCell, only can load the first two

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.item % 2 == 0) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CaptureNameTableViewCell", for: indexPath) as! CaptureNameTableViewCell
        cell.nameTextField.text = ""
        cell.nameTextField.tag = indexPath.row
        cell.nameTextField.delegate = self
        return cell
    } else if indexPath.section == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CapturePhotoTableViewCell", for: indexPath) as! CapturePhotoTableViewCell
        cell.displayImage = imageView
        cell.cellDelegate = self
        cell.selectImage.tag = indexPath.row
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PieChartTableViewCell", for: indexPath) as! PieChartTableViewCell
        return cell
    }
}

Solution

  • You need to register the xib tableViewCells inside of the tableViewController:

    First create an id property inside of the cells xib class, to use as the cell’s reuse identifier (make the name of this the same as your reuse identifier for the cell which you set in the xib file):

    let id = "cellIdentifier" // Name this appropriately
    

    Then create a nib method inside of the cell's xib class:

    func nib() -> UINib {
        return UINib(named: "cellIdentifier", bundle: nil)
    }
    

    Then inside of a lifecycle method such as viewDidLoad():

    tableView.register(nib: cell.nib, forCellReuseIdentifier: cell.id)
    

    Finally, specify which cells you want to be where in the table view at which indexPath.row. (Which row in the table view):

    switch indexPath.row {
        case 0: // First cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "CaptureNameTableViewCell", for: indexPath) as! CaptureNameTableViewCell
            // Configure cell as before
            return cell
        case 1: // Second cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "CapturePhotoTableViewCell", for: indexPath) as! CapturePhotoTableViewCell
            // Configure cell as before
            return cell
        case 2: // Third cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "PieChartTableViewCell", for: indexPath) as! PieChartTableViewCell
            // Configure cell as before
            return cell
        default:
            return UITableViewCell() // This should not be reached but a switch statement must cover all possibilities.
    }