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
Asked
Active
Viewed 2,852 times
1 Answers
11
Here are a few ways to accomplish communication between your objects.
- 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.
- 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.
- 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()
}
}

PixelCloudSt
- 2,805
- 1
- 18
- 19
-
great explanation...but what i trying to do is create object for parentcontroller in childcontroller.so i can access parentcontroller method from childcontroller.can u help me on this? – user3823935 Feb 10 '15 at 10:28
-
The delegate pattern can do what you are asking of it (giving the child controller an object to control the parent with). You have to pass the parentcontroller to the childcontroller in order to get ahold of it. – PixelCloudSt Feb 10 '15 at 17:14
-
If you really need to get the instance of the parentcontroller object and don't have any ability to pass it in to the child from the parent you could do something really ugly like a singleton. Frankly, when you're considering using singletons, in many cases, it's time to rethink your architecture, imo. – PixelCloudSt Feb 10 '15 at 17:20