添加半透明视图最简单的方法

Posted 预估计

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了添加半透明视图最简单的方法相关的知识,希望对你有一定的参考价值。

项目中需要实现点击按钮出现的视图全屏覆盖,呈半透明状态可以看到下面的视图?

解决方案:

绕了很多弯路原来可以使用模态弹出一个视图控制器

ios8之后只需要设置一个最新的属性

 

SecondViewController *vc=[[SecondViewController alloc]init];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;这句代码很重要
    [self presentViewController:vc animated:NO completion:^{
//        vc.view.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
        vc.view.backgroundColor = [UIColor orangeColor];
        vc.view.alpha = 0.5;
    }];

在iOS7或更低需要设置你的window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext

AppDelegate *appdelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    UIViewController *vc=[[UIViewController alloc]init];
    appdelegate.window.rootViewController.modalPresentationStyle=UIModalPresentationCurrentContext;
    [appdelegate.window.rootViewController presentViewController:vc animated:YES completion:^{
        vc.view.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
        appdelegate.window.rootViewController.modalPresentationStyle=UIModalPresentUIModalPresentationFullScreen;
    }];

实现完成后发现了一个bug, 如果当presentingVC有根视图控制器tabBarController,上面的设置会使tabBar未被覆盖,意思就好像是你有一直看到presentingVC直接导致不会走viewWiillAppear,不能在原视图即将出现时把隐藏tabBar的属性改回来。此时

在present的时候敲一行

self.tabBarController.tabBar.hidden = YES; // 隐藏tabBar

在dismiss的时候敲一行

 

self.presentingViewController.tabBarController.tabBar.hidden = NO; // 先获取弹出视图的视图控制器,再修改隐藏属性

 

以上是关于添加半透明视图最简单的方法的主要内容,如果未能解决你的问题,请参考以下文章