How to access the main window from controllers in Objective-C?

I am creating a custom view controller called HomeViewController , which inherits from UIViewController . In the main application, I show it by calling [window addSubview:homeViewController.view] inside the applicationDidFinishLaunching function. Yes, everything works well.

Now I am adding a button to the HomeViewController xib file. When I click on it, I want the window remove the current view and add another navigationController instead. I make a function inside HomeViewController.m and reference the button, but I don’t know how to access the window property from there. window is a local variable inside the main delegate of the application, and the button click handler is inside the HomeViewController . I am thinking of doing a similar thing as stated above, which is to add navigationController.view as a window .

Sorry! I am very new to developing this iphone application. I really don't understand how the flow of applications should be. Perhaps something is wrong with the structure of my project?

+6
source share
3 answers

You can access the main window anywhere in the application using the bottom line

 [[[UIApplication sharedApplication] windows] objectAtIndex:0] 
+11
source

[(AppDelegate *)[[UIApplication sharedApplication] delegate] window] can help you access the delegate's window property.

AppDelegate is the name of your delegate.

+4
source

You can add an extension for the UIViewController. In Swift:

 extension UIViewController { var window : UIWindow { return UIApplication.shared.windows.first! } } 

Now you can access it from any view controller. For instance:

 override func viewDidLoad() { super.viewDidLoad() self.window.tintColor = .orange } 

Allegedly, you should have a window, so you can safely force the window to expand, however you can just make it optional if you do something else with your window hierarchy:

 extension UIViewController { var window : UIWindow? { return UIApplication.shared.windows.first } } 

Implementation using options:

 override func viewDidLoad() { super.viewDidLoad() if let window = self.window { window.tintColor = .orange } } 
0
source

Source: https://habr.com/ru/post/901585/


All Articles