简体   繁体   中英

How to call method from another class in Swift 4.0

I am working an an app that involves a wheel. I want to execute a function in another class when the angular velocity reaches 0 after being spun.

The setup is that I have a SKView embedded in a view controller. I have a class called WheelView that is tied to that SKView.

Full class: https://github.com/swiftishard/wheelpractice2/blob/master/WheelView.swift This is the relevant portion of code.

class WheelDelegate: NSObject, SKSceneDelegate {



func didSimulatePhysics(for scene: SKScene) {

    guard let wheelScene = scene as? WheelScene else { return }
    if (wheelScene.wheel.physicsBody?.angularVelocity ?? 0.0) > 0.0 {
        print(wheelScene.wheel.physicsBody?.angularVelocity)
        if(wheelScene.wheel.physicsBody?.angularVelocity ?? 0.0) < 25.0 {
            wheelScene.wheel.physicsBody?.angularVelocity = 0.0
            if(wheelScene.wheel.physicsBody?.angularVelocity ?? 0.0) == 0.0 {

                print("CALL METHOD FROM ANOTHER VIEW CONTROLLER")

            }

        }
    }
}

}

Main view controller where method to call is located

  import UIKit

class Main: UIViewController {
    func methodToCall() {
        print("METHOD CALLED")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


}

So how would I call methodToCall from the didSimulatePhysics code?

I'm assuming WheelDelegate is created within Main as an object.

Multiple ways you can do this:

1) Most common way I have seen is to create a protocol as well as some delegates.

Inside Main class, right below all the imports, you can do.

protocol ViewControllerTalkingDelegate {
    func methodToCall()
}

Inside WheelDelegate you add this as a global variable

var delegate:ViewControllerTalkingDelegate?

Then, whenever you create WheelDelegate inside Main

let wheelDelegate = WheelDelegate()
wheelDelegate.delegate = self

Then, inside Main at the bottom, you can do

extension Main:ViewControllerTalkingDelegate {
    func methodToCall() {
         //Do Something
    }
}

Now, inside WheelDelegate you can do delegate.methodToCall() .

2) Other way I have seen is to pass the 1st class as a variable to the 2nd class.

Inside WheelDelegate add a global variable

var myViewController:Main?

You can then either take in Main as a parameter when initializing or when you create WheelDelegate you can do

var wheelDelegate = WheelDelegate()
wheelDelegate.myViewController = self

Then inside WheelDelegate you can do

self.myViewController.methodToCall()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM