Is it possible to create one tableViewCell that can be used in multiple Table Controllers?

前端 未结 2 1602
孤街浪徒
孤街浪徒 2020-12-04 04:12

I have about 3 or 4 table controllers that will all use the same tableview cell. I keep going back on fourth of the possible logic. Can I use the same tableViewCell in multi

相关标签:
2条回答
  • 2020-12-04 04:31

    Yes you can use the table view cell in multiple tableView Controllers .

    0 讨论(0)
  • 2020-12-04 04:37

    Yes you can.

    I am assuming that you are using Swift.

    Goto File -> New and select cocoaTouch class as follows.

    Now name Your class for custom cell and make it subClass of UITableViewCell. also check the box which says "Also create Xib file"

    Now design your cell in this Xib and create outlets in its .Swift file. Lets say you have a custom tableView cell which looks something like this

    Which contains a label or ImageView or anyThing that you have in your cell. Now in your swift file of custom cell you can write a method like so

    class func cellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath) -> YourCustomTableViewCell {
    let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
    tableView.registerNib(UINib(nibName: "YourCustomTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
    
    let cell = tableView.dequeueReusableCellWithIdentifier(kYourCustomTableViewCellIdentifier, forIndexPath: indexPath) as! YourCustomTableViewCell
    
    return cell
    }
    

    Now you can use this cell in any tableView in your application just like below

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let cell = YourCustomTableViewCell.cellForTableView(tableView, atIndexPath: indexPath)
    cell.backgroundColor = UIColor.clearColor()
    // do something with your cell
    
    }
    

    I hope it helps.

    Update for Swift 3 and Swift 4:

    class func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> YourCustomTableViewCell {
        let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
        tableView.register(UINib(nibName: "YourCustomTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
    
        let cell = tableView.dequeueReusableCell(withIdentifier: kYourCustomTableViewCellIdentifier, for: indexPath) as! YourCustomTableViewCell
    
        return cell
    }
    
    0 讨论(0)
提交回复
热议问题