一、抽出一个工具类,遮罩层 创建、添加、删除
下载地址:https://download.csdn.net/download/wangxiaoertedaye/11071728
1.初始化半透明view ,添加单击手势(为了删除遮罩层)
2.添加遮罩层到当前window方法
3.移除方法
@interface MaskView : UIView
-(instancetype)initWithFrame:(CGRect)frame;
+(instancetype)makeViewWithMask:(CGRect)frame andView:(UIView*)view;
-(void)block:(void(^)(void))block;
@end
#import "AppDelegate.h"
@implementation MaskView
//初始化View以及添加单击蒙层逻辑
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.frame = frame;
//在这里需要用下边的方法设定Alpha值,第一种方法会使子视图的Alpha值和父视图的一样.
// self.backgroundColor = [UIColor colorWithRed:(40/255.0f) green:(40/255.0f) blue:(40/255.0f) alpha:1.0f];
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
self.userInteractionEnabled = YES;
UITapGestureRecognizer *pan = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeView)];
[self addGestureRecognizer:pan];
}
return self;
}
//蒙层添加到Window上
+(instancetype)makeViewWithMask:(CGRect)frame andView:(UIView*)view{
MaskView *mview = [[self alloc]initWithFrame:frame];
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[delegate.window addSubview:mview];
[mview addSubview:view];
return mview;
}
//单击蒙层取消蒙层
-(void)removeView{
// 去掉点击任意地方,消失遮罩层
[self removeFromSuperview];
}
//通过回调取消蒙层
-(void)block:(void(^)(void))block{
[self removeFromSuperview];
block();
}
@end
二、具体使用
在需要使用VC引入该工具类
1.显示遮罩层
//该方法是点击按钮是显示遮罩层,
- (void)openCGyanhuoView:(UIButton *)button{
_maskView = [MaskView makeViewWithMask:CGRectMake(0, 0, ScreenWidth, ScreenHeight) andView:self.yanhuoView];
}
2.移除遮罩层
//点击按钮(可以是确定按钮、完成按钮、键盘return按钮) 移除遮罩层
//工具类提供点击任意遮罩层位置,移除遮罩层如不需要可注释创建时的 单击手势
- (void)closeView:(UIButton *)btn{
[_maskView block:^{
}];
}