Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference UITableViewController from a UITableViewCell class?

I have the following:

  1. UITableViewController
  2. UITableView
  3. Custom UITableViewCell subclass

I used a .xib file for the cell, which is a CustomCell subclass. This custom cell handles IBActions for some touch events on the cell's buttons.

I'd like to reference the ViewController and some of its variables from the cell.

How am I supposed to access the UITableViewController from the UITableViewCell class?

like image 430
Norly Canarias Avatar asked Oct 20 '14 14:10

Norly Canarias


1 Answers

I wouldn't create this kind of dependency between the cell and the view controller - that makes the architecture more intricate and the cell not reusable.

I suggest you to use the delegation pattern, which may sound a little complicated - although you're already using (UITableViewDelegate is a typical example):

  • create a protocol MyCellProtocol with one method didTapCell, accepting a UITableViewCell and/or some custom data you want to pass to the view controller
  • create a public delegate property in your custom cell: weak var cellDelegate: MyCellProtocol?
  • in the didTapXXX handler or didSelectRowAtIndexPath of your cell, call self.cellDelegate?.didTapCell(), passing the expected parameters
  • in your view controller, implement the MyCellProtocol
  • in cellForRowAtIndexPath of your view controller, when creating/dequeuing the cell, set its cellDelegate property to self

At this point, when a tap is done in your cell, the didTapCell method of the view controller is called, and from there you can do whatever you need to achieve.

The key point is: rather than making the cell handle the cell tap/selection, notify the view controller and let it do the job.

like image 89
Antonio Avatar answered Sep 17 '22 08:09

Antonio