展示后,我想立即解雇,但只能在2秒后再做。这个怎么做?

这是我从UILabel上的UITapGestureRecognizer调用的方法。

- (IBAction)labelTaped:(UITapGestureRecognizer *)sender {
  if (sender.state == UIGestureRecognizerStateEnded) {
    CGRect frame = CGRectNull;
    NSString *message = nil;
    // ...
    // some code
    /// ...
    if (message) {
        // show info alert
        __weak __typeof(self)weakSelf = self;
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleActionSheet];

        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"alert_ok", @" - ")
                                                               style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 if ([weakSelf.dismissAlertTimer isValid]) {
                                                                     [weakSelf.dismissAlertTimer invalidate];
                                                                 }
                                                             }];
        [alert addAction:cancelAction];

        UIPopoverPresentationController *popoverController = alert.popoverPresentationController;
        popoverController.sourceRect = frame;
        popoverController.sourceView = sender.view;


        [self.mainController presentViewController:alert animated:YES completion:^{
            if ([weakSelf.dismissAlertTimer isValid]) {
                [weakSelf.dismissAlertTimer invalidate];
            }
            weakSelf.dismissAlertTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:weakSelf selector:@selector(dismissAlertController) userInfo:nil repeats:NO];
        }];
    }
  }
}

- (void)dismissAlertController {
    [self.mainController dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

最佳答案

最简单的是这样吗?

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"message dismiss in 2 seconds" preferredStyle:UIAlertControllerStyleAlert];

[self presentViewController:alertController animated:YES completion:nil];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    [alertController dismissViewControllerAnimated:YES completion:^{
        // do something ?
    }];

});

还是意味着您还希望阻止用户在触发2秒之前点击取消按钮?

关于ios - UIAlertController仅在2秒后关闭,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27396852/

10-10 20:49