Swift - Delegate a non-caller from another class

I am trying to change the text of a label in another view controller on a button click. This is how I set up the delegate:

In FirstViewController under import UIKit

@objc protocol MyDelegate{
    optional func makeScore()
}

      

In FirstViewController under class FirstViewController: UIViewController

var delegate:MyDelegate?

      

In FirstViewController on button click

delegate?.makeScore!()

      

In SecondViewController (where is makeScore()

)

class SecondViewController: UIViewController, MyDelegate

      

Method makeScore()

in SecondViewController

func makeScore() {
    println("worked")
}

      

It doesn't register anything when the button is pressed. I'm pretty sure I have configured delegates and protocols correctly. Do you see something missing?

Note: FirstViewController

and are SecondViewController

not linked by sections. They are both in scrollView

.

+3


source to share


1 answer


Now I see that you have added a second view controller programmatically with these lines:

let vc6 = storyboard.instantiateViewControllerWithIdentifier("Second") as! SecondViewController
self.addChildViewController(vc6)
self.scrollView.addSubview(vc6.view)

      

Just add one line so it reads like this:



let vc6 = storyboard.instantiateViewControllerWithIdentifier("Second") as! SecondViewController
self.delegate = vc6
self.addChildViewController(vc6)
self.scrollView.addSubview(vc6.view)

      

Edit: On the node side, I'm pretty sure the delegate is actually the best approach to what you are trying to do. Your best bet is probably to globally link to yours SecondViewController

and then call self.vc6.makeScore()

. Delegates are commonly used to call objects that are not contained in the view controller

+3


source







All Articles