user3823935
user3823935

Reputation: 891

Call parentController method from childcontroller in swift

I am doing a simple customtableview project.I have viewController.swift and customcell.swift file.I have a method inside viewcontroller file.How do i call that method from customcell file.any help will be appreciated.thanks in advance

Upvotes: 3

Views: 2872

Answers (1)

PixelCloudSt
PixelCloudSt

Reputation: 2805

Here are a few ways to accomplish communication between your objects.

  1. You could use the delegation pattern and basically set the viewcontroller as a delegate for the customcell instance. The customecell object would then call the desired method on the delegate when it needed to.
  2. You could setup a closure in the viewcontroller object that calls the desired method, and then pass that closure down to the customcell object for use when you want to execute the viewcontroller's method from the customcell instance.
  3. You could use NSNotifications to communicate from the customcell to the viewcontroller. The customcell would "post" a notification, and the view controller (after having registered to "observe" that particular notification) could call whatever method needed to be executed.

There are other ways to go about this, but those are the first three that come to mind. Hope that gave you a few ideas on how to proceed.

Below is a simple example of the delegation pattern.

Your parent would 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 would look like this:

class Child
{
    weak var delegate : ParentProtocol?

    func callDelegate () {
        delegate?.method()
    }

}

Upvotes: 11

Related Questions