如何从UITableViewCell类引用UITableViewController? [英] How to reference UITableViewController from a UITableViewCell class?
问题描述
我有以下内容:
- UITableViewController
- UITableView
- 自定义UITableViewCell子类
我为该单元格使用了一个.xib文件,这是一个 CustomCell
子类。此自定义单元格会处理该单元格按钮上某些触摸事件的IBAction。
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.
我想从单元格中引用ViewController及其一些变量。
I'd like to reference the ViewController and some of its variables from the cell.
我如何应该从UITableViewCell类访问UITableViewController?
How am I supposed to access the UITableViewController from the UITableViewCell class?
推荐答案
我不会在单元格和视图之间创建这种依赖关系
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.
我建议您使用委派模式,这听起来可能有些复杂-尽管您已经在使用使用( UITableViewDelegate
是一个典型示例):
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
使用一种方法didTapCell
,接受UITableViewCell
和/或某些自定义方法您想要传递给视图控制器的数据 - 在自定义单元格中创建一个公共委托属性:
弱变量cellDelegate:MyCellProtocol?
- 在
didTapXXX
处理程序或didS中您的单元格的elecRowAtIndexPath
,调用self.cellDelegate?.didTapCell()
,传递期望的参数 - 在视图控制器中,在视图的
cellForRowAtIndexPath
中实现MyCellProtocol
- 控制器,在创建/删除单元格时,请将其
cellDelegate
属性设置为self
- create a protocol
MyCellProtocol
with one methoddidTapCell
, accepting aUITableViewCell
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 ordidSelectRowAtIndexPath
of your cell, callself.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 itscellDelegate
property toself
这时,当您在单元格中完成轻按时,将调用视图控制器的 didTapCell
方法,
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.
这篇关于如何从UITableViewCell类引用UITableViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!