用Swift语言代理 [英] Delegate in Swift-language

查看:79
本文介绍了用Swift语言代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器,我需要调用第一个控制器到第二个控制器的功能:
在第二个控制器中,我在课堂上创建了协议和init委托:

I have two controllers and i need call up function the first controller to second controller: In second controller I have created protocol and init delegate in class:

    protocol testProtocol {
        func testDelegate() // this function the first controllers
    }

    class SecondViewController: UIViewController {
        var delegate: testProtocol?
    ....
    }
    @IBAction func testDelegateClicked(sender : AnyObject) {
            delegate?.testDelegate()
        }

第一个控制器

First Controller


        class ViewController: UIViewController, testProtocol {

但是没有调用函数

推荐答案

我将假设您正在使用故事板。如果我是正确的,那么你的问题是在你的第一个控制器中创建的 secondController 不是你提出的实际的。您需要在 prepareForSegue中设置 secondController

I am going to make an assumption you are using storyboards. If I am correct, then your issue is that your secondController, created in your First Controller, is not the actual one you are presenting. You will need to set secondController in your prepareForSegue:

不变

class ViewController: UIViewController, testProtocol {

    // you will want to add the ? since this variable is now optional (i.e. can be nil)
    var secondController: SecondViewController? // don't assign it a value yet

    // ...

    // implementation of the protocol
    func testDelegate() {
        println("Hello delegate")
    }

    // your prepare for segue
    override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
        // get the controller that storyboard has instantiated and set it's delegate
        secondController = segue!.destinationViewController as? SecondViewController
        secondController!.delegate = self;
    }
}

这篇关于用Swift语言代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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