天天看点

用UIWindow作为弹出视图的遮罩层

关键点:

1、要把要显示的window定义为一个static变量。

   这样,它不会在方法结束后被销毁。

2、不需要将window add 到某个view或window上去。

    只要alloc了一个window,并且window.hiden = NO,则这个window就会显示了。

static UIWindow *__sheetWindow = nil;

@implementation ViewController

-(void)addWindowAction{

    UIWindow *window = [[UIWindow alloc] initWithFrame:(CGRect) {{0.f, 0.f}, [[UIScreen mainScreen] bounds].size}];

    window.backgroundColor = [UIColor clearColor];

    window.windowLevel = UIWindowLevelNormal;

    window.alpha = 1.f;

    window.hidden = NO;

    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 100, 100)];

    UIButton* btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    btn.frame = CGRectMake(10, 10, 20, 20);

    [view addSubview:btn];

    [btn addTarget:self action:@selector(removeWindowAction) forControlEvents:UIControlEventTouchUpInside];

    view.backgroundColor = [UIColor redColor];

    [window addSubview:view];

    __sheetWindow = window;

}

-(void)removeWindowAction{

    __sheetWindow.hidden = YES;

    __sheetWindow = nil;

}

@end