Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share custom UITableViewCell to multiple UITableViewController in Swift

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?

like image 955
Haw Avatar asked Aug 11 '26 02:08

Haw


1 Answers

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!
}
like image 91
He Yifei 何一非 Avatar answered Aug 14 '26 16:08

He Yifei 何一非



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!