NathanVss
NathanVss

Reputation: 644

iOS reuse table cells design

I'm building a youtube like app to train myself to Swift and Autolayout.

But I'm facing a problem, in multiple places I need to display a table of videos, then what I want to do is to design one video's cell that I'll reuse in other tables but I don't see how to do that.

I tried to put a ContainerView in a cell be I got this error "Container Views cannot be placed in elements that are repeated at runtime."

PS : I already thought of a ContainerView referencing a TableViewController of videos, but the problem is that Videos are not the only cells that I want to have in my differents tables. ( Sometimes there is comments at the bottom, sometimes other things etc. Shortly: The tables will have different types of cells ).

Upvotes: 1

Views: 896

Answers (1)

bradkratky
bradkratky

Reputation: 1617

Use a separate xib file to create reusable table cells. So you create CustomTableViewCell.swift and CustomTableViewCell.xib. To use your custom cell, you need to register it in the UITableViewDataSource.

This stackoverflow answer may be of use.

 import UIKit
class TableViewController: UITableViewController {
    let items = ["Item 1", "Item2", "Item3", "Item4"]

     override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerNib(UINib(nibName: "CustomOneCell", bundle: nil), forCellReuseIdentifier: "CustomCellOne")
    }

 // MARK: - UITableViewDataSource

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomCellOne", forIndexPath: indexPath) as! CustomOneCell
        cell.middleLabel.text = items[indexPath.row]
        cell.leftLabel.text = items[indexPath.row]
        cell.rightLabel.text = items[indexPath.row]
        return cell
    }
 }

Upvotes: 3

Related Questions