Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Function in a ViewController from UITableViewCell

How can I call a function of a ViewController from a custom tableview cell of a UITableView in that ViewController (using SWIFT)?

like image 815
shaydawg Avatar asked Aug 18 '15 09:08

shaydawg


2 Answers

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()
  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
  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)
  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
like image 72
Adnan Aftab Avatar answered Sep 23 '22 13:09

Adnan Aftab


Post a notification from your cell:

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

Then listen out for it in your viewController:

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

Make sure you define the new function in your viewController:

func functionToCall() {
    //This function will be called when you post the notification
}
like image 37
Swinny89 Avatar answered Sep 24 '22 13:09

Swinny89