Search code examples
iphoneiosuiwindow

AppDelegate UIWindow addSubView in different viewController


I am trying to add a UILabel in UIWindow of AppDelegate from a UIViewController. This is how I am doing this:

AppDelegate code :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
    } else {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
    }



    [self.window makeKeyAndVisible];

    self.window.rootViewController = self.viewController;


    return YES;
}

ViewController code :

- (void)viewDidLoad
{

    UILabel *abcd=[[UILabel alloc] initWithFrame:CGRectMake(100.0, 100.0, 200.0, 40.0)];

    abcd.text=@"loading...";

    abcd.backgroundColor=[UIColor clearColor];

    [[[[UIApplication sharedApplication] delegate] window] addSubview:abcd];

    [super viewDidLoad];


}  

But all I am seeing is grey screen but no label. Where I might be going wrong?


Solution

  • 1) I suggest you reverse the order of your last two delegate statements:

    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    

    2) While you should be able to add the label to the window, its somewhat unorthodox to do so. In any case, try adding the label to the viewController's view and see if that works, and if so, and you really want to add it to the window (for some reason), then add a comment here:

    [self.view addSubview:abcd];
    

    If you still cannot see the label its likely that there is an issue with the view controller. Did you define anything in the nib - any element that should be visible at launch ? If not then add something just so you can be sure the view is in fact getting loaded. [One trick I use is to set the background color of views to red or blue, so I can see that in fact they got loaded.]