如何在Swift中从uitableviewcell类中引用控制器 [英] How to reference controller from a uitableviewcell class in Swift

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

问题描述

我有以下


  1. ViewController

  2. tableView

  3. CustomCell

我为单元格使用了NIB(.xib文件),它使用CustomCell类。这个自定义单元格类处理IBAction一些触摸单元格的按钮。我想引用ViewController及其中的一些变量。我应该怎么做(访问ViewController)?

I used a NIB(an .xib file) for the cell, which uses a CustomCell class. This custom cell class handles IBAction for some touch on the cell's button. I'd like to reference the ViewController and some of its variables within it. How am I supposed to do it(accessing ViewController)?

谢谢!

推荐答案

我不会在单元格和视图控制器之间创建这种依赖关系 - 这使得结构更复杂,并且单元格不可重用。

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 和/或您要传递给视图控制器的某些自定义数据

  • 在自定义单元格中创建公共委托属性:在 didTapXXX 处理程序或<$ c $>中添加code> var cellDelegate:MyCellProtocol?

  • c> c> didSelectRowAtIndexPath ,传递预期的参数

  • self.cellDelegate?.didTapCell li>在您的视图控制器中,实现 cellForRowAtIndexPath 中的 MyCellProtocol
    您的视图控制器在创建/出列单元格时,将其 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: 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.

关键点是:而不是使单元格处理单元格tap /选择,通知视图控制器并让它做这项工作。

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

这篇关于如何在Swift中从uitableviewcell类中引用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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