0

I am trying to call a method from one view controller into another view controller, but it's not working. I also tried looking into similar StackOverflow problems but I wasn't able to get an answer.

Method from the First View Controller that I want to call (class is called SoprtsController)

Second View Controller where I want to call the method (class is called LastViewController

Coder44
  • 1
  • 1
  • 1
    Always include code as text and not images and you shouldn’t really be calling a function in one view controller from another view controller, that is not how MVC works. – Joakim Danielson Aug 11 '22 at 21:21

2 Answers2

0

Like someone else mentioned it's usually not good practice to call another view controller's functions.

Make sure your variable test has a value before you try to use it.

Inside of viewDidLoad you can set a value test = SportsController() Or set a value when creating whatever view controller you're in. lastVC.test = SportsController()

Next time post your code in the question! It makes it easier to see the problem.

func getCurrentSport() -> sports? {
   return currentSport
}
var selectedSport: sports?
var test: SportsController?
var testSport: sports?

override func viewDidLoad() {
   super.viewDidLoad()
   testSport = test?.getCurrentSport()
   print(testSport?.sportName)
}
0

You could use NotificationCenter. I only do this if I need to update a view in the presenting view controller before dismissing the current view controller.

Add the following to the view controller that contains the method you are calling:

private let notification = NotificationCenter.default

override func viewDidLoad() {
    super.viewDidLoad()
    addObservers()
}

private func addObservers() {
    notification.addObserver(self, selector: #selector(myMethod(_:)), name: Notification.Name.identifier, object: nil)
}

@objc
func myMethod(_ notification: Notification) {
    // Do whatever
}

Then add the following to the view controller you are calling the method from:

func callTheMethod() {
    NotificationCenter.default.post(name: Notification.Name.identifier, object: self, userInfo: nil)
}
GIJoeCodes
  • 1,680
  • 1
  • 25
  • 28