@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];
}
}