ios - 从 UITableViewCell 调用 ViewController 中的函数

标签 ios swift uitableview

如何从 ViewController 中的 UITableView 的自定义 tableview 单元调用 ViewController 的函数(使用 SWIFT)?

最佳答案

有几种方法可以做到这一点

  1. Delegation (创建协议(protocol)委托(delegate) uitableViewcell)将 View Controller 设置为 UITabelVeiwCell 的委托(delegate),然后从单元调用 self.delegate.whatEverDeelgate()
  2. 从单元格发布通知并在 View Controller View 内为该通知注册观察者 NSNotificationCenter.defaultCenter().addObserver(self, selector: "nameOfSelector", name: "Name Of Notification", object: nil) 然后从 tableView 单元格 postNotification,但确保你也想删除 Observer,访问这个 link了解更多详情
  3. 在 UITableViewCell 中保留 viewController 的弱引用,意味着创建一个属性 @weak var viewController:YourViewcontroller 并使用它来调用 View Controller 上的方法(不推荐)
  4. 在关键路径上添加观察者 aka KVO (这将在属性更改其值时调用 View Controller 中的方法)对于您的场景可能不是必需的

关于ios - 从 UITableViewCell 调用 ViewController 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32068689/

相关文章:

ios - 以编程方式截取图像

ios - 我们可以使用按钮代替 Collection View 吗?

ios - 在选择 UITableViewCell 时旋转图像

ios - 我需要经常更新 TableView 但这样做会复制单元格

ios - 当且仅当运行时到达代码块内部时才导入类

ios - 用户打字时覆盖变暗

ios - 台风 + swift : Crash when using run-time arguments

swift - 在 Swift 中发布 Feed 数据建模

objective-c - 自动将 XIB 文件调整为屏幕大小

iphone - iOS 7 下 UITableView 部分索引相关的崩溃