Find UIAlertView without having reference to it
I'm writing application tests and want to check if an UIAlertView is currently shown. That means I don't have a pointer to it and I need to know who is the owner of the开发者_Go百科 shown UIAlertView or on which views stack it can be found.
[UPDATE] Actually the solution below is not working for iOS 7, because the alert views are not bound to a specific window any more. Read here for details: https://stackoverflow.com/a/18703524/942107
Based on KennyTM'm advice in another question Sebastien provided link to, I've created a UIAlertView category with a method returning the UIAlertView if shown to be able to dismiss it programatically.
UIAlertViewAdditions.h:
#import <UIKit/UIKit.h>
@interface UIAlertView (UIAlertViewAdditions)
+ (UIAlertView *) getUIAlertViewIfShown;
@end
UIAlertViewAdditions.m:
#import "UIAlertViewAdditions.h"
@implementation UIAlertView (UIAlertViewAdditions)
+ (UIAlertView *) getUIAlertViewIfShown {
if ([[[UIApplication sharedApplication] windows] count] == 1) {
return nil;
}
UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
if ([window.subviews count] > 0) {
UIView *view = [window.subviews objectAtIndex:0];
if ([view isKindOfClass:[UIAlertView class]]) {
return (UIAlertView *) view;
}
}
return nil;
}
@end
精彩评论