从swift中的childcontroller调用parentController方法 [英] Call parentController method from childcontroller in swift

查看:107
本文介绍了从swift中的childcontroller调用parentController方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个简单的customtableview项目。我有viewController.swift和customcell.swift文件。我在viewcontroller文件中有一个方法。如何从customcell文件调用该方法。任何帮助将不胜感激。谢谢提前

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

推荐答案

以下是完成对象之间通信的几种方法。

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


  1. 您可以使用授权模式并基本上将viewcontroller设置为customcell实例的委托。然后,customecell对象将在需要时在代理上调用所需的方法。

  2. 您可以设置closure 调用所需的方法,然后将该闭包传递给customcell对象,以便在您想要执行viewcontroller的方法时使用customcell instance。

  3. 您可以使用 NSNotifications 从customcell到viewcontroller。 customcell将发布通知,并且视图控制器(在注册观察特定通知之后)可以调用需要执行的任何方法。

  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()
    }

}

这篇关于从swift中的childcontroller调用parentController方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆