3

Currently, I have two table view controllers which contain some identical custom tableview cells. Each table view controller has its own custom tableview cells. I'm wishing to create only one custom table view cell which can be shared among these two table view controllers. Any guides can I refer to?

He Yifei 何一非
  • 2,592
  • 4
  • 38
  • 69
Haw
  • 43
  • 7

1 Answers1

6

First you can create a UITableViewCell with code: (and you can design your cell view in a .xib file - see here for detail)

// MyCell.Swift

import UIKit
import Foundation

class MyCell: UITableViewCell {
    // do whatever you want to customize the cell
}

Then in each of your two UITableViewController's classes, register your custom UITableViewCell class in viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.register(MyCell.self as AnyClass, forCellReuseIdentifier: "cell")
}

Then create/reuse this custom cell in cellForRowAtIndexPath function:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: MyCell? = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MyCell
    if cell == nil {
        // if the cell is not yet created in the system, create a new cell object
        cell = MyCell(style: .default, reuseIdentifier: "cell")
    }

    // customize your cell...
    cell.textLabel?.text = "Your Label Text"

    return cell!
}
Community
  • 1
  • 1
He Yifei 何一非
  • 2,592
  • 4
  • 38
  • 69