tounaobun tounaobun - 3 months ago 21
iOS Question

How to detect whether UIAlertView is currently showing

Is there any way to judge whether there is currently a

UIAlertView
instance showing? Because it is possible to show multiple
UIAlertView
in the same window level.

if ([self isAlertViewShowing]) {
// do not show UIAlertView again.
} else {
// show your UIAlertView.
}


Hope there is such a method called
isAlertViewShowing
or something else.

Answer

Method 1- Initialize default flag for alert... If alert is not open set isAlertViewShowing as NO

    Bool isAlertViewShowing;
    isAlertViewShowing = NO;
    if (isAlertViewShowing == NO){
         UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
         [alert show];
         // Now set isAlertViewShowing to YES
         isAlertViewShowing = YES;
    }
    else
    {
         //Do something
    }

Method 2- Make your own function to check whether any UIAlertView is showing or not

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

I recommended to use second method if number of UIAlertView instance may be more than one.

Comments