简体   繁体   中英

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?

您可以使用以下行访问应用中任何位置的主窗口

[[[UIApplication sharedApplication] windows] objectAtIndex:0]

[(AppDelegate *)[[UIApplication sharedApplication] delegate] window] might help you to access window property of a delegate.

AppDelegate is your delegate class name.

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
    }
}

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