AppDelegate UIWindow addSubView in different viewController

Nitish picture Nitish · Aug 29, 2012 · Viewed 14.1k times · Source

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?

Answer

alfonsomiranda picture alfonsomiranda · Aug 29, 2012

You must not add UILabel to UIWindow, you should add to UIViewController. Change this line:

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

for this:

[self.view addSubview:abcd];