Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I create a custom view controller named HomeViewController which inherits from UIViewController. In main application delegate, I show it by calling [window addSubview:homeViewController.view] inside function applicationDidFinishLaunching. Yeah, everything works fine.

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

Sorry! I'm very new to this iphone app development. I don't really get the big picture of how the application flow should be. Perhaps something's wrong with the structure of my project?

like image 360
Davuth Avatar asked Nov 16 '11 03:11

Davuth


2 Answers

You can access main window any where in your app using below line

[[[UIApplication sharedApplication] windows] objectAtIndex:0]
like image 51
Narayana Avatar answered Oct 25 '22 22:10

Narayana


You can add an extension to UIViewController. In Swift:

extension UIViewController {

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

}

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

override func viewDidLoad() {
    super.viewDidLoad()

    self.window.tintColor = .orange
}

Ostensibly you should have a window, so you should be able to safely force unwrap the window, however, you can just make it optional if you are doing something different with your window hierarchy:

extension UIViewController {

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

}

Implementation using optionals:

override func viewDidLoad() {
    super.viewDidLoad()

    if let window = self.window {
        window.tintColor = .orange
    }
}
like image 30
Matt Long Avatar answered Oct 25 '22 21:10

Matt Long