How to reference UITableViewController from a UITableViewCell class?(如何从 UITableViewCell 类中引用 UITableViewController?)
问题描述
我有以下几点:
- 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):
- 使用一种方法
didTapCell创建一个协议MyCellProtocol,接受UITableViewCell和/或您想要传递给视图控制器的一些自定义数据 - 在您的自定义单元格中创建一个公共委托属性:
weak var cellDelegate: MyCellProtocol? - 在单元格的
didTapXXX处理程序或didSelectRowAtIndexPath中,调用self.cellDelegate?.didTapCell(),并传递预期的参数李> - 在您的视图控制器中,实现
MyCellProtocol - 在视图控制器的
cellForRowAtIndexPath中,在创建/出列单元格时,将其cellDelegate属性设置为self
- create a protocol
MyCellProtocolwith one methoddidTapCell, accepting aUITableViewCelland/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
didTapXXXhandler ordidSelectRowAtIndexPathof your cell, callself.cellDelegate?.didTapCell(), passing the expected parameters - in your view controller, implement the
MyCellProtocol - in
cellForRowAtIndexPathof your view controller, when creating/dequeuing the cell, set itscellDelegateproperty 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 UITableViewCell 类中引用 UITableViewController?
基础教程推荐
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
