iOS之UIAlertView點選視窗之外區域關閉
阿新 • • 發佈:2019-01-05
彈出一個UIAlertView,然後點選視窗之外的區域來關閉UIALertView,程式碼如下:
- (IBAction)showAlert:(id)sender { 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; [[UIApplication sharedApplication].keyWindow 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]; } } }