Search code examples
iosswiftcustom-cell

How to edit masterDetailView template to allow custom cells within tableview


I have created a custom class called CustomeTableViewCell which includes the code:

@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!

Within my master view controller I have two bits of code displayed below.

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let coursework = fetchedResultsController.object(at: indexPath)
    configureCell(cell, withCoursework: coursework)

    return cell
}

   func configureCell(_ cell: UITableViewCell, withCoursework coursework: Coursework) {
    cell.textLabel?.text = databaseTest.name

}

My question is how can I edit this piece of code to allow multiple labels within the cofigureCell. so the function looks like this :

  func configureCell(_ cell: UITableViewCell, withCoursework coursework: Coursework) {
       cell.label1.text = databaseTest.name
       cell.label2.text = databaseTest.surname

  }

I am quite new to swift coding therefore any feedback is always appreciated.


Solution

  • When you dequeue your cells, you should cast them into CustomeTableViewCell.

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomeTableViewCell
    

    Then by changing the cell type in your function, you'll be able to set all labels.

    func configureCell(_ cell: CustomeTableViewCell, withCoursework coursework: Coursework) {