Call the parentController method from childcontroller in swift

I am doing a simple customtableview project. I have a viewController.swift and a customcell.swift file. I have a method inside the viewcontroller file. How I call this method from the customcell file. Our help will be appreciated. thanks in advance

+1
source share
1 answer

Here are some ways to achieve communication between your objects.

  • You can use the delegation template and basically configure the viewcontroller as a delegate for the customcell instance. Then the customecell object will call the required method for the delegate, when necessary.
  • You can configure closure in the viewcontroller object that calls the desired method, and then pass this closure to the customcell object for use when you want to execute the viewcontroller method from a customcell instance.
  • You can use NSNotifications to communicate with the custom cell with the view manager. The user cell "sent" a notification, and the view controller (after registering to "watch" this particular notification) could call any method that needs to be executed.

There are other ways to do this, but these are the first three that come to mind. Hope this gave you some ideas on how to proceed.

The following is a simple example of a delegation pattern.

Your parent will look like this:

protocol ParentProtocol : class { func method() } class Parent { var child : Child init () { child = Child() child.delegate = self } } extension Parent : ParentProtocol { func method() { println("Hello") } } 

Your child will look like this:

 class Child { weak var delegate : ParentProtocol? func callDelegate () { delegate?.method() } } 
+10
source

Source: https://habr.com/ru/post/987329/


All Articles