彈框點選內容以外的空白處消失
阿新 • • 發佈:2019-01-03
@implementation AlertView { UIView *_contentView; UILabel *_titleLabel; } + (instancetype)alertView{ return [[self alloc] init]; } - (instancetype)init; { self = [super init]; if (self) { [self setUpSubViews]; } return self; } - (void)setUpSubViews{ self.frame = [UIScreen mainScreen].bounds; self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3]; self.alpha = 0; // 內容區域 _contentView = [[UIView alloc] init]; _contentView.backgroundColor = [UIColor whiteColor]; _contentView.layer.cornerRadius = 8; _contentView.layer.masksToBounds = YES; _contentView.transform = CGAffineTransformMakeScale(0.05, 0.05); // _titleLabel = [[UILabel alloc] init]; _titleLabel.backgroundColor = kColorTheme; _titleLabel.font = kNormalFont(17); _titleLabel.text = @"提示"; _titleLabel.textColor = [UIColor whiteColor]; _titleLabel.textAlignment = NSTextAlignmentCenter; [self addSubview:_contentView]; [_contentView addSubview:_titleLabel]; [_contentView mas_makeConstraints:^(MASConstraintMaker *make) { make.center.equalTo(self); make.width.mas_equalTo(kScreenWidth-40); make.height.mas_greaterThanOrEqualTo(270); }]; [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.left.top.right.equalTo(_contentView); make.height.mas_equalTo(44); }]; } - (void)setTitle:(NSString *)title{ _title = title; _titleLabel.text = title; } - (void)show{ [[UIApplication sharedApplication].keyWindow addSubview:self]; [UIView animateWithDuration:0.3 animations:^{ self.alpha = 1; _contentView.transform = CGAffineTransformMakeScale(1, 1); }]; } - (void)disMiss{ [UIView animateWithDuration:0.3 animations:^{ self.alpha = 0; _contentView.transform = CGAffineTransformMakeScale(0.05, 0.05); }completion:^(BOOL finished) { [self removeFromSuperview]; }]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; point = [_contentView.layer convertPoint:point fromLayer:self.layer]; if (![_contentView.layer containsPoint:point]) { [self disMiss]; } } @end
核心程式碼:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; // 拿到觸控點 UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; // 觸控點相對於內容部分的位置 point = [_contentView.layer convertPoint:point fromLayer:self.layer]; // 如果觸控點不在內容部分 則讓彈窗消失 if (![_contentView.layer containsPoint:point]) { [self disMiss]; } }