用Swift语言代表

时间:2014-06-05 11:37:29

标签: ios uiviewcontroller swift ios8

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

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

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

第一控制器         

        class ViewController: UIViewController, testProtocol {

var secondController: SecondViewController = SecondViewController() override func viewDidLoad() { super.viewDidLoad() secondController.delegate = self } func testDelegate() { println("Hello delegate") }</pre>

但是没有调用函数

1 个答案:

答案 0 :(得分:12)

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

中设置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;
    }
}