一行代碼簡單實現遮罩層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:^{
        
    }];
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章