简体   繁体   中英

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];
}

这是做你想做的事的一种方式:

[[UIApplication sharedApplication].keyWindow addSubview:overlayView];

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];
}

斯威夫特3

UIApplication.shared.keyWindow?.addSubview(overlayView);

you can try like this

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *overlayView = [[UIView alloc] initWithFrame:self.view.frame];

    overlayView.backgroundColor = [UIColor blackColor];
    overlayView.alpha = 0.8;
    overlayView.center = self.view.center
    [self.view addSubview:overlayView];
}

i hope will helpful for you...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM