繁体   English   中英

iOS Objective-C 在当前显示的 UIAlertController 上获取参考

[英]iOS Objective-C Get Reference on Currently Displayed UIAlertController

我想获得当前显示的UIAlertController的参考。

(有些人认为我的问题很糟糕,并对其进行了投票。然而他们错了,因为有一个问题的答案,我会发布它,所以其他对此感兴趣的人可以找到它!)

我用一个弱引用创建了一个单例类,然后我扩展了UIAlertController并创建了一个新方法来呈现它,在那里我将这个弱引用设置为新显示的警报。 现在,只要它有任何其他引用,它就会保存警报的引用,因此在显示时。

UIAlertController+扩展.h

@interface UIAlertController(Extension)

- (UIAlertController*)showIn:(UIViewController*)viewController;
+ (UIAlertController*)lastOnScreenAlert;

@end

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

有一个通用的解决方案来获取支持多个窗口的当前警报控制器,并且可以与呈现自己警报的第三方库一起使用:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM