How do I call a method from another class in Swift?

16,309

Solution 1

Syntactically, it seems like you're trying to accomplish what a static method normally does. Unless this is what you're trying to accomplish, and I'm guessing it's not, you need to instantiate your SecondViewController before you call a method on it, assign it to a variable, and call your desired method as follows:

let otherViewController: SecondViewController = SecondViewController()
let result = otherViewController.doSomething()

If you're trying to transition (segue) to another view controller when you click on the button you should be using the prepareForSegue() method to make the transition to the next view controller. Also, don't forget to set the segue identifier on the Storyboard.

Hopefully this is helpful.

Solution 2

First of all, you have to keep a reference to an instance of SecondViewController in your FirstViewController. Then, in order to call a function foo() in SecondViewController from your FirstViewController, just call secondInstance.foo(). If foo() is class function, you can call with SecondViewController.foo().

class A : UIViewController {
    var myB  = B()

    func callBFoo() {
        myB.foo()
    }

    func callStaticBFoo() {
        B.staticFoo()
    }
}

class B : UIViewController {
    func foo() {
        println("foo")
    }

    class func staticFoo() {
        println("static foo")
    }
}
Share:
16,309
smecperson
Author by

smecperson

Updated on June 04, 2022

Comments

  • smecperson
    smecperson almost 2 years

    When a button is pressed in FirstViewController, I would like for it to call a func pressedButton() in another class (SecondViewController). How do I do this?

    I've tried the following, and it does not work right:

    SecondViewController().pressedButton()
    

    Here's the code for pressedButton:

    func pressLearnButton() {
            let screenSize: CGRect = UIScreen.mainScreen().bounds
            let screenWidth = screenSize.width
            self.scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0), animated: true)
        }