I have the following:
- UITableViewController
- UITableView
- 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?
I don't think you should do that and probably you're doing something wrong but if you really-really need it then just have a property in your
CustomCell
class.then when you create the cell in
cellForRowAtIndexPath
set the propertyafter that you can easily access the view controller from within the cell code:
But again, in my opinion, you should redesign your code. The cell should not care about the controller. It should care only about displaying itself and nothing else
Best way is to implement Delegation. Your delegate will inform the view controller about the button click. And, In turn your view controller (who is conforming the protocol for above delegate) will handle the task that you want to perform on click event. (Delegation pattern tutorials are available online. you can go through them if you want to know how to do delegation).
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):MyCellProtocol
with one methoddidTapCell
, accepting aUITableViewCell
and/or some custom data you want to pass to the view controllerweak var cellDelegate: MyCellProtocol?
didTapXXX
handler ordidSelectRowAtIndexPath
of your cell, callself.cellDelegate?.didTapCell()
, passing the expected parametersMyCellProtocol
cellForRowAtIndexPath
of your view controller, when creating/dequeuing the cell, set itscellDelegate
property toself
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.
Read the other comments about really wanting to use an alternate approach before trying this, but using this extension will allow you to get to the
dataSource
anddelegate
both of which should be theUITableViewController
add Extension
now downCast as below
.
Inside your cell