如何从 UITableViewCell 类中引用 UITableViewController? [英] How to reference UITableViewController from a UITableViewCell class?

查看:12
本文介绍了如何从 UITableViewCell 类中引用 UITableViewController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

  1. UITableViewController
  2. UITableView
  3. 自定义 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 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

此时,当在您的单元格中完成点击时,将调用视图控制器的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆