Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a single prototype cell in multiple tableViews?

I am having two different tableviews in two different controller. But the cells, that I need to display in them, look identical. I have created a prototype cell in one tableView and subclassed UiTableViewCell. Now, if I want to use the same cell in a different controller, how can I use it ?

If I just import that customCell file in the new controller and deque it using the same identifier given in the storyboard, it wont work. It says

Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

So, clearly it means , the cell is nil. So how can I instantiate the same cell from the storyboard ? Is it possible or do I have to create a different customCell for the new table too ?

like image 434
akshaynhegde Avatar asked Oct 22 '12 04:10

akshaynhegde


2 Answers

K.. I got it. First of all,

I can NOT use one prototype cell in two different tableview. But, I can use the same tableViewCell subclass in two different tableviews.

To achieve it, one just have to copy the prototype cell from one controller and paste it as a prototype cell of the other tableview. Class of the pasted tableview remains the same. Just change the reuseIdentifier. and use it.

Edit: If your cell has a fairly complicated UI, then it makes more sense to create separate xib for the cell alone. Then programmatically register the xib with the table view. That way, you will have only one copy of the cell and much better at maintaining it when there are changes to the ui.

like image 155
akshaynhegde Avatar answered Nov 14 '22 02:11

akshaynhegde


You can use same prototype cell in different view controllers, you just need to dequeue it from the tableview of controller in which you designed it.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let viewControllerInWhichCellWasDefined = tabBarController?.viewControllers?[0]   
  let cell = viewControllerInWhichCellWasDefined.tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)
  return cell
}
like image 26
Vitaly Avatar answered Nov 14 '22 01:11

Vitaly