skip to Main Content

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

2

Answers


  1. 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)
    }
    
    Login or Signup to reply.
  2. 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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search