{
UIAlertView *alert;
UITapGestureRecognizer *recognizerTap;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
button.frame = CGRectMake(100, 100, 100, 100);
[button addTarget:self action:@selector(actionButton) forControlEvents:(UIControlEventTouchUpInside)];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
}
- (void)actionButton
{
alert = [[UIAlertView alloc] initWithTitle:@"模态测试"
message:@"请点击四周的模态区域我就消失"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
recognizerTap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleTapBehind:)];
[recognizerTap setNumberOfTapsRequired:1];
recognizerTap.cancelsTouchesInView = NO;
[alert.window addGestureRecognizer:recognizerTap];
}
- (void)handleTapBehind:(UITapGestureRecognizer *)sender{
if (sender.state == UIGestureRecognizerStateEnded) {
CGPoint location = [sender locationInView:nil];
if (![alert pointInside:[alert convertPoint:location fromView:alert.window] withEvent:nil]) {
[alert.window removeGestureRecognizer:sender];
[alert dismissWithClickedButtonIndex:0 animated:YES];
}
}
}