[英]iOS Objective-C Get Reference on Currently Displayed UIAlertController
I wanted to get a reference on the currently displayed UIAlertController
.我想获得当前显示的
UIAlertController
的参考。
(Some guys thought my question sucks and close voted it. However they were wrong, as there IS an answer to the question and I will post it, so others interested in this can find it!) (有些人认为我的问题很糟糕,并对其进行了投票。然而他们错了,因为有一个问题的答案,我会发布它,所以其他对此感兴趣的人可以找到它!)
I've made a singleton class with one weak reference, then I've extended UIAlertController
and made a new method to present it, where I set this weak reference to the newly displayed alert.我用一个弱引用创建了一个单例类,然后我扩展了
UIAlertController
并创建了一个新方法来呈现它,在那里我将这个弱引用设置为新显示的警报。 Now this will hold the reference of the alert as long as it has any other reference, thus while it is displayed.现在,只要它有任何其他引用,它就会保存警报的引用,因此在显示时。
UIAlertController+Extension.h UIAlertController+扩展.h
@interface UIAlertController(Extension)
- (UIAlertController*)showIn:(UIViewController*)viewController;
+ (UIAlertController*)lastOnScreenAlert;
@end
UIAlertController+Extension.m UIAlertController+Extension.m
@interface LastAlert : NSObject
@property (nonatomic, weak) UIAlertController* reference;
@end
static LastAlert* lastAlert;
@implementation LastAlert
+ (void)initialize
{
[super initialize];
lastAlert = [LastAlert new];
}
@end
@implementation UIAlertController(Extension)
- (UIAlertController*)showIn:(UIViewController*)viewController
{
[viewController presentViewController:self animated:YES completion:nil];
[LastAlert class];
lastAlert.reference = self;
return self;
}
+ (UIAlertController*)lastOnScreenAlert
{
return lastAlert.reference;
}
@end
There is a common solution to get the current alert controller that supports multiple windows and can work with third party libraries which present their own alerts:有一个通用的解决方案来获取支持多个窗口的当前警报控制器,并且可以与呈现自己警报的第三方库一起使用:
static UIAlertController* currentAlertController() {
for (UIWindow* window in UIApplication.sharedApplication.windows) {
UIViewController* presented = window.rootViewController.presentedViewController;
while (presented != nil) {
if ([presented isKindOfClass:UIAlertController.class]) {
return (UIAlertController *)presented;
}
presented = presented.presentedViewController;
}
}
return nil;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.