Delegate in Swift-language

前端 未结 1 1043
傲寒
傲寒 2020-12-17 22:11

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:

<
相关标签:
1条回答
  • 2020-12-17 22:37

    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:

    Second Controller

    Unchanged

    First Controller

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题