Access the instance of a Viewcontroller from another in swift

前端 未结 3 1985
刺人心
刺人心 2020-12-04 18:21

I am trying to transfer data from the textfield of one View Controller to the label from another.

How can I call the View Controller instance from the code of the o

3条回答
  •  情深已故
    2020-12-04 18:44

    Imanou Petit and Oscar Swanros already answered correctly. However there is an alternative which is rather "hacky" that I had to use to transfer data between 2 view controllers without a segue connecting them.

    To obtain the root view controller of your app you can do:

    UIApplication.sharedApplication().windows[0].rootViewController
    

    From there you can get any view controller you want. For instance, if you want the second child view controller of the root view controller then you would do:

    let viewController = UIApplication.sharedApplication().windows[0].rootViewController?.childViewControllers[1] as? YourViewController
    viewController?.yourProperty = newValue
    

    Keep in mind that this approach is rather "hacky" and probably violates the best coding practices.

提交回复
热议问题