//
//效果图如上
下面直接上代码
#import <UIKit/UIKit.h>
@interface MaskView : UIView<UIGestureRecognizerDelegate>
-(instancetype)initWithFrame:(CGRect)frame;
+(instancetype)makeViewWithMask:(CGRect)frame andView:(UIView*)view;
-(void)block:(void(^)())block;
@end
#import "MaskView.h"
#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 lightGrayColor] colorWithAlphaComponent:1];
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(^)())block{
[self removeFromSuperview];
block();
}
@end
#import "MaskViewController.h"
#import "MaskView.h"
#import "AppDelegate.h"
@interface MaskViewController ()
@property (nonatomic ,strong)MaskView *maskView;
@end
@implementation MaskViewController
- (void)viewDidLoad {
[super viewDidLoad];
//添加一个添加蒙层按扭
self.view.backgroundColor = [UIColor whiteColor];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-50, 100, 100, 40)];
btn.backgroundColor = [UIColor yellowColor];
[btn setTitle:@"添加蒙层" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
[btn addTarget:self action:@selector(btn:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)btn:(UIButton *)sender{
UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-75, 100, 150, 150)];
btn1.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
[btn1 setTitle:@"取消蒙层" forState:UIControlStateNormal];
//在蒙层上放的控件调用取消蒙层逻辑
[btn1 addTarget:self action:@selector(btn1:) forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview:btn1];
//添加蒙层,以及蒙层上放的控件
_maskView = [MaskView makeViewWithMask:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) andView:btn1];
}
-(void)btn1:(UIButton *)sender{
//取消蒙层
[_maskView block:^{
NSLog(@"取消之后");
}];
}