Swift delegate

I have two controllers, and I need to call the function of the first controller for the second controller: In the second controller, I created a protocol and delegate init to the 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 {

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

But the function does not receive the call

+7
ios uiviewcontroller ios8 swift
source share
1 answer

I'm going to make the assumption that you are using storyboards. If I am right, then your problem is that your secondController created in your first controller is not the actual one that you represent. You need to set secondController in prepareForSegue:

Second controller

Without changes

First controller

 class ViewController: UIViewController, testProtocol { // you will want to add the ? since this variable is now optional (ie 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 delegate secondController = segue!.destinationViewController as? SecondViewController secondController!.delegate = self; } } 
+12
source share

All Articles