How to add view in UIWindow?

Prajeet Shrestha picture Prajeet Shrestha · Mar 20, 2015 · Viewed 25.3k times · Source

I wanted to add a view in UIWindow with following code:

 AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
 UIWindow *window = delegate.window;
 UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
 aView.backgroundColor = [UIColor blackColor];
 [window addSubview:aView];

This code didn't work. I wanted to clone property of UIAlertView. It will pop over top of everything when we call [alertViewInstance show]; method.

Tried this as well:

   UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    UIWindow* window = [UIApplication sharedApplication].keyWindow;

    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }

    [window addSubview:aView];
    [window bringSubviewToFront:aView];

Answer

Vishal16 picture Vishal16 · Dec 25, 2015

If are you using UINavigationController Use:

[self.navigationController.view.window addSubview:aView];

If are you using UITabBarController Use:

[self.tabBarController.view.window addSubview:aView];

In AppDelegate you can directly assign a view to window. In appDelegate didFinishLaunchingWithOptions method Use:

[self.window addSubview:aView];

Hope it helps...