简体   繁体   中英

RootViewController won't add subview when accessed outside its delegate

I have this code compiled with no error, but I can't make welcomeUIView to be displayed.

Yes, when I move it inside didFinishLaunchingWithOptions it will show up. But why I can't make it the way I want?

Here is the console out:

didFinishLaunchingWithOptions
view()
finished

The code:

AppDelegate.h

#import <UIKit/UIKit.h>
static UIWindow *window;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@end 

AppDelegate.mm

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
std::cout<<"didFinishLaunchingWithOptions"<<std::endl;
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.rootViewController = [[UIViewController alloc] init];

view *v = new view();
v->set();

// Override point for customization after application launch.
window.backgroundColor = [UIColor whiteColor];
[window makeKeyAndVisible];

std::cout<<"finished"<<std::endl;

return YES;
}

view.mm

#include "view.h"
#include "AppDelegate.h"
#include <UIKit/UIKit.h>
#include <iostream>

void view::set()
{
std::cout<<"view()"<<std::endl;

UIView *welcomeUIView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[welcomeUIView setBackgroundColor:[UIColor darkGrayColor]];

[welcomeUIView setHidden:false];
[window.rootViewController.view addSubview:welcomeUIView];
[window.rootViewController.view bringSubviewToFront:welcomeUIView];
}

You can easily add the view in your root view controller. Do it in viewDidLoad

-(void)viewDidLoad {
    [super viewDidLoad]; 

    UIView *welcomeView = 
          [[UIView alloc] initWithFrame:self.view.bounds];
    welcomeView.backgroundColor = UIColor.darkGrayColor;
    [self.view addSubview:welcomeView];
}

This will, however not cover the whole screen if you have a status bar or navigation bar. Instead, you can add the view to self.view.window (with the CGRect from your code).

The bug is that window is declared as static in your header, so each translation unit will have its own distinct window .

You've set the window variable within AppDelegate.mm, but then in view.mm you have a different window which is still nil. If you meant to share window you should declare is extern in your header and then define it within AppDelegate.mm.

Also, you should just let your view controller set up its own view hierarchy by subclassing UIViewController and overriding loadView .

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