简体   繁体   English

从UITableViewCell调用ViewController中的函数

[英]Call Function in a ViewController from UITableViewCell

我如何可以调用的函数ViewController从一个自定义的tableview细胞UITableViewViewController (使用SWIFT)?

There are few ways you can do that 你可以用很少的方法做到这一点

  1. Delegation (create a protocol delegate uitableViewcell) set view controller as delegate of UITabelVeiwCell and then from cell call self.delegate.whatEverDeelgate() 委托 (创建协议委托uitableViewcell)将视图控制器设置为UITabelVeiwCell委托,然后从单元调用self.delegate.whatEverDeelgate()
  2. Post notification from the cell and register observer for that notification inside view controller view NSNotificationCenter.defaultCenter().addObserver(self, selector: "nameOfSelector", name: "Name Of Notification", object: nil) and then from tableView cell postNotification, but make sure you want to removeObserver as well, visit this link for more detail 从单元格发布通知并在视图控制器视图中注册该通知的观察者NSNotificationCenter.defaultCenter().addObserver(self, selector: "nameOfSelector", name: "Name Of Notification", object: nil)然后从tableView单元格postNotification,但请确保您也想删除Observer,请访问此链接以获取更多详细信息
  3. Keep a weakReference of viewController inside UITableViewCell, means create a property @weak var viewController:YourViewcontroller and use this to call method on view controller (Not recommended) 在UITableViewCell中保持viewController的weakReference,意味着创建一个属性@weak var viewController:YourViewcontroller并使用它来调用视图控制器上的方法(不推荐)
  4. Add observer on a key path aka KVO (this will call a method in view controller when a property changes its value) may be not necessary for your scenario 在关键路径上添加观察者,即KVO (当属性更改其值时,将在视图控制器中调用方法)对于您的场景可能不是必需的

Post a notification from your cell: 发布您单元格的通知:

NSNotificationCenter.defaultCenter().postNotificationName("notificationName", object: nil)

Then listen out for it in your viewController: 然后在viewController中监听它:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "functionToCall", name: "notificationName", object: nil)

Make sure you define the new function in your viewController: 确保在viewController中定义新函数:

func functionToCall() {
    //This function will be called when you post the notification
}

You can declare a protocol in your UIableViewCell class. 您可以在UIableViewCell类中声明protocol

Make your ViewController delegate of this protocol. 使您的ViewController委托该协议。

On some action from your cell, call this delegate method. 在您的单元格中执行某些操作时,请调用此委托方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM