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

实现思路:

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 废话不多说,直接上干货 ---------------------------------------------...
    小小赵纸农阅读 3,436评论 0 15
  • 概述 UIView或者它的子类知道怎样将自己绘制在一个矩形区域中。我们app所有可视的的界面来自于视图。创建和配置...
    smalldu阅读 900评论 0 6
  • { 24、Sqlite数据库 1、存储大数据量,增删改查,常见管理系统:Oracle、MSSQLServer、DB...
    CYC666阅读 962评论 0 1
  • 开端 2016年07月31日第8次Startups Toastmaster演讲活动中,我担任了英文主持人的角色,这...
    袁春楠阅读 491评论 0 2
  • 感恩今天晴朗的天气。 感恩卖衣服的美女态度好,发现衣服有个小瑕疵积极的处理。 感恩今早虽然很冷但坚持起来户外运动。...
    莀宝贝阅读 129评论 0 0