Search code examples
iosxcodeuitableviewreuseidentifier

Register cell reuse identifier within XCode Playgrounds


Trying to play with Table in the XCode Playgrounds to understand how it works, because there a lot of stuff connected to the UITableView and a few tutorials describe these relations and inheritance under the scenes (like UIView -> UIScrollView -> UITableView -> UITableViewCell) and how it manages that inheritance, connections and delegations. Normally with an ordinary tutor, you're given with snippet of code and the instructions how to establish delegate connections in XCode and the right methods to call. Result - you memorize the steps but still don't understand the mechanism of the Table. Below is code snippet that I try to adopt for XCode Playgrounds to draw a simple table. The problem - I can't properly register programmatically reuse identifier for Table cell nether from class or outside it. The nature of error

reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'.

Please, help and point out what is wrong and why.

class TableViewController: UITableViewController {

let tableData = ["Matthew", "Mark", "Luke", "John"]

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableData.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = tableData[indexPath.row]
    return cell
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.dataSource = self
//Did this part as comments to try to do this outside the class   
//        self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
//        self.tableView = UITableView(frame:self.view.frame)
//        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    self.view.addSubview(self.tableView)

}

}
let frame = CGRect(x: 0, y: 0, width: 320, height: 480)
let tableView = UITableView(frame: frame, style: .plain)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
PlaygroundPage.current.liveView = TableViewController()

Solution

  • In a UIViewController contaning a UITableView, programmatically registering of Custom UITableViewCell Subclasses to an instance of UITableView is implemented by:
    - (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier

    This is registeringClass should be done before setting up table's dataSource.