Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Delegate not calling method from other class

I'm trying to change a label's text in another view controller when a button is pressed. Here's how I'm setting 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 when a button is pressed

delegate?.makeScore!()

In SecondViewController (where makeScore() is located)

class SecondViewController: UIViewController, MyDelegate

The makeScore() method in SecondViewController

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

It's not logging anything when the button is pressed. I'm pretty sure I set up delegates and protocols correctly. Do you see anything missing?

Note: FirstViewController and SecondViewController are not connected by segues. They are both in a scrollView.

like image 551
smecperson Avatar asked Jan 30 '26 01:01

smecperson


1 Answers

I can see now you added the second view controller programmatically with the these lines:

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

Just add one line, so that it reads like this:

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

Edit: On a side node, I'm sure a delegate is actually the best approach for what you're trying to do. You'd probably be better off just making a global reference to your SecondViewController, then calling on self.vc6.makeScore(). Delegates are typically used for calling back to objects that are not contained in the View Controller

like image 119
Mike V Avatar answered Feb 01 '26 14:02

Mike V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!