Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add UIView object to self.view.window in ios7?

I'd like to add a dark view layer that covers the whole screen.

In order to do that, I added UIView object to window property of UIViewController as shown below.I remember I was able to add a view to window like this in ios6. But, it doesn't work in ios7.

How am I able to make it work?

Thanks in advance!!

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *overlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];

    overlayView.backgroundColor = [UIColor blackColor];
    overlayView.alpha = 0.8;

    [self.view.window addSubview:overlayView];
}
like image 693
crzyonez777 Avatar asked Feb 04 '14 09:02

crzyonez777


2 Answers

Here's one way of doing what you want:

[[UIApplication sharedApplication].keyWindow addSubview:overlayView];
like image 70
Gad Avatar answered Nov 17 '22 13:11

Gad


According to the documentation of UIView, the window property is nil if the view has not yet been added to a window which is the case when viewDidLoad is called.

You can do the same thing in viewDidAppear:(BOOL)animated;

- (void)viewDidAppear:(BOOL)animated; {
    UIView *overlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];

    overlayView.backgroundColor = [UIColor blackColor];
    overlayView.alpha = 0.8;
    [self.view.window addSubview:overlayView];
}
like image 9
Bonnie Avatar answered Nov 17 '22 15:11

Bonnie