tags:

views:

49

answers:

2

I am trying to add another subview programmatically based on some event (user taps a button, for instance).

My problem is that I am having problems referencing the (one and only) instance of UIWindow. I reach it from my appDelegate, because the MainWindow.xib and the appDelegate have been wired up. But I cannot reach the UIWIndow from anywhere else (I cannot draw that connection in IB, can I?)

What techniwue is preferred to get a reference to (the one and only) UIWindow? ...so that I in turn can use the following code from my various UIViewControllers:

[myOneAndOnlyWindow addSubview:oneOfManyViews.view];
[myOneAndOnlyWindow makeKeyAndVisible];
+1  A: 

You can use following code to add view in main window from any view controller:

YourAppDelegate *appDelegate = (YourAppDelegate*)[[UIApplication sharedApplication] delegate];
[appDelegate.window addSubView:viewController.view];

The only thing you must take care is that window should be defined as a property in your application delegate class.

Hope this helps.


Jim.

Jim
Thanks Jim, it did the trick, although it feels kinda wrong to have to reference the appDelegate from the sub viewController. On the other hand - the MainWindow.xib belongs to the appDelegate after all. But...how about delegation? Could that be used here somehow?
maralbjo
+3  A: 

You can retrieve pointer to the key window of your application after call [UIApplication sharedApplication].keyWindow Window becomes key after you call [window makeKeyAndVisible]

FalconSer
Very interesting. This method must surely be the preferred one (over the one below), since you do not need a pointer back to the appDelegate?
maralbjo