美文网首页iOS知识点程序员iOS Developer
iOS--弹出视图后使window背景变暗

iOS--弹出视图后使window背景变暗

作者: 尼古拉斯超仔 | 来源:发表于2017-04-01 10:01 被阅读834次

    实现思路:

    1,首先要拿到window (方式有多重可以app delegate,或者创建window、keywindow等等方式)。
    2. 然后创建一个backgroundView,使其frame和window相等,设置背景颜色,再添加到window上。
    3.把需要显示的view添加到backgroundView上,当然有动画效果更好,通过改变view的frame来实现view的显示与隐藏。

    代码如下

    #define SCREENWIDTH  [UIScreen mainScreen].bounds.size.width
    #define SCREENHEIGHT  [UIScreen mainScreen].bounds.size.height
    
    #import "ViewController.h"
    @interface ViewController ()
    @property (strong, nonatomic)UIView *bgView;//半透明背景
    @property (strong, nonatomic)UIView *alertView;//假设为弹窗
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((SCREENWIDTH-100)/2, 50, 100, 100)];
        btn.backgroundColor = [UIColor yellowColor];
        [self.view addSubview:btn];
        [btn addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
    }
    - (void)show{
        //1. 取出window
        UIWindow * window = [[UIApplication sharedApplication] keyWindow];
        //2. 创建背景视图
        _bgView = [[UIView alloc]init];
        _bgView.frame = window.bounds;
        //3. 背景颜色可以用多种方法
        _bgView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        //    _bgView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.6];
        [window addSubview:_bgView];
        //4. 把需要展示的控件添加上去
        _alertView = [[UIView alloc ]initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 49)];
        _alertView.backgroundColor = [UIColor greenColor];
        [window addSubview:_alertView];
        //5. 动画简单(low)
        [UIView animateWithDuration:0.3 animations:^{
            _alertView.frame = CGRectMake(0, SCREENHEIGHT-49, SCREENWIDTH, SCREENHEIGHT);
        }];
        //6.给背景添加一个手势,后续方便移除视图
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideAlertView)];
        [_bgView addGestureRecognizer:tap];
    }
    - (void)hideAlertView{
        //动画简单(low)
        [UIView animateWithDuration:0.3 animations:^{
            _alertView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 49);
        }];
        // 延迟几秒移除视图
        [self performSelector:@selector(remove) withObject:nil afterDelay:0.3];
    }
    - (void)remove{
        [_bgView removeFromSuperview];
    }
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    @end
    

    相关文章

      网友评论

      本文标题:iOS--弹出视图后使window背景变暗

      本文链接:https://www.haomeiwen.com/subject/lgtiottx.html