How to add view in UIWindow?
Solution 1
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...
Solution 2
Try with this code:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
aView.backgroundColor = [UIColor redColor];
aView.center = window.center;
[window insertSubview:aView aboveSubview:self.view];
[window bringSubviewToFront:aView];
}
Solution 3
Try this code:
window = [[UIApplication sharedApplication].windows lastObject];
Replace the following code:
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
Solution 4
Your windows needs to have a root view controller.
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UIWindow *window = delegate.window;
UIViewController *controller = [[UIViewController alloc] init];
window.rootViewController = controller;
UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
aView.backgroundColor = [UIColor blackColor];
[controller.view addSubview:aView];
Solution 5
You can add view using the following
[[[UIApplication sharedApplication] keyWindow] addSubview:YOUR_VIEW];
Prajeet Shrestha
I started my journey to the programming world with PHP, jQuery. I stumbled into iOS by luck. And I instantly fell in love with iOS environment. I love every bit of my work. I am being paid for what I love to do. It's awesome. I am totally into Swift right now. And focus on protocol oriented programming. I have started a blog recently. Please feel free to contact me any time :)
Updated on July 12, 2022Comments
-
Prajeet Shrestha almost 2 years
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];