一行代码简单实现遮罩层MaskView

一、抽出一个工具类,遮罩层 创建、添加、删除

下载地址: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:^{
        
    }];
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值