Check if a UIAlertView is showing

后端 未结 10 1345
刺人心
刺人心 2020-11-27 16:45

I have a method that posts HTTP data and displays a UIAlertView if there is an error. If I have multiple HTTP post I will show multiple UIAlertView for every error.

相关标签:
10条回答
  • 2020-11-27 17:25

    Swift:

    func showAlert(withTitle title: String, message: String, viewController: UIViewController) {
        if viewController.presentedViewController == nil { // Prevent multiple alerts at the same time
            let localizedTitle = NSLocalizedString(title, comment: "")
            let localizedMessage = NSLocalizedString(message, comment: "")
            let alert = UIAlertController(title: localizedTitle, message: localizedMessage, preferredStyle: .Alert)
            let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
            alert.addAction(action)
    
            viewController.presentViewController(alert, animated: true, completion: nil)
        }
    }
    
    0 讨论(0)
  • 2020-11-27 17:37
    + (BOOL)checkAlertExist {
    
        for (UIWindow* window in [UIApplication sharedApplication].windows) {
            if ([window.rootViewController.presentedViewController isKindOfClass:[UIAlertController class]]) {
                return YES;
            }
        }
        return NO;
    }
    
    0 讨论(0)
  • 2020-11-27 17:39

    If you can control the other alert views, check the visible property for each of them.


    In iOS 6 or before, when an alert appears, it will be moved to a _UIAlertOverlayWindow. Therefore, a pretty fragile method is to iterate through all windows and check if there's any UIAlertView subviews.

    for (UIWindow* window in [UIApplication sharedApplication].windows) {
      NSArray* subviews = window.subviews;
      if ([subviews count] > 0)
        if ([[subviews objectAtIndex:0] isKindOfClass:[UIAlertView class]])
          return YES;
    }
    return NO;
    

    This is undocumented as it depends on internal view hierarchy, although Apple cannot complain about this. A more reliable but even more undocumented method is to check if [_UIAlertManager visibleAlert] is nil.

    These methods can't check if a UIAlertView from SpringBoard is shown.

    0 讨论(0)
  • 2020-11-27 17:42

    Why not just check the visible property, maintained by the UIAlertView class?

    if (_alert) //alert is a retained property
    {
        self.alert = [[[UIAlertView alloc] initWithTitle:@"Your Title"
                                                 message:@"Your message" 
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:@"OK"] autorelease];
    }
    if (!_alert.visible)
    {
        [_alert show];
    }
    
    0 讨论(0)
提交回复
热议问题