简体   繁体   中英

How to call non-static method from static method of the viewController class in swift?

Hello I would like to know how to call a non static method from static method in the UIViewController class.

what i did is:

 public static func cambiarPosicion(posicion: Int){

    var reserva :   ReservaViewController = ReservaViewController()

    reserva.cambiarContainer(posicion: posicion)

} 

But for calling the method that I want in the UIViewController I have created a instance of the same viewController(ReservaViewController) as you see. Then I used it for call a method called cambiarContainer but I have a problem in that method, the error is:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

and some code that I have in that method and where I have the error is:

self.btnSelectUbicacion.setBackgroundImage(#imageLiteral(resourceName: 
    "fondo_transparente"), for: .normal)
self.btnSelectServicio.setBackgroundImage(nil, for: .normal)
self.btnSelectHora.setBackgroundImage(#imageLiteral(resourceName: 
  "fondo_transparente"), for: .normal)
self.btnConfirmacionReserva.setBackgroundImage(#imageLiteral(resourceName: 
  "fondo_transparente"), for: .normal)

The error is in the first line I think that this problem is because I am calling the method from another instance, it is for that reason that I would like to know how to call a non method static from a static method.

Because a static field/method--by definition--is not tied to any single object/instance of the class, while a non-static field/method always refers to an actual object/instance in some way.

So, you can't call non static method inside static method.

Think of a class as a factory. Say we have a Car class. The class is the factory that makes the cars. An instance of a Car is an actual car, in a specific color, with a license tag, that belongs to somebody.

You can tell an instance of car to set its radio to a given station. It doesn't make sense to do that from the factory however. ("Hey car factory, set the radio on Bob's car to 'Hits 101'").

If you use storyboard or.xib file with UIViewController, you should create the controller with create its storyboard or.xib:

with.xib file:

ViewController(nibName: "ViewController", bundle: nil)

with.storyBoard:

 let storyboard = UIStoryboard(name: "storyboardName", bundle: nil)
 let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerIdentifier")

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