【问题标题】:Get presentViewController from non view class (Objective-C)从非视图类获取presentViewController(Objective-C)
【发布时间】:2021-09-24 16:58:02
【问题描述】:

我正在尝试用 UIAlertController 替换对已弃用 UIAlertView 的调用。显示警报的类不是视图控制器,所以我不确定用什么来代替“self presentViewController”。

对于背景,这是我使用 UIAlertView 显示警报的方式:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];

这是我打算使用 UIAlertController 替换的:

UIAlertController *alert  = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];

但是,如前所述,我不能从这个位置使用“self presentViewController”,所以我尝试像这样获取(并使用)视图控制器:

UIViewController *viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
[viewController presetViewController:alert animated:YES completion:nil];

上面的代码导致编译错误,“No visible @interface for 'UIViewController' declarations selector 'presetViewController:animated:completion:'”。

我应该如何解决这个问题?

谢谢!

PS:不用我说很明显,但我是一个 Objective-C 新手。我花了 20 多年的时间在其他操作系统上编写 c++……

【问题讨论】:

    标签: objective-c uialertview uialertcontroller presentviewcontroller


    【解决方案1】:

    此代码:[viewController:alert animated:YES completion:nil]; 不正确。应该是[viewController presentViewController:alert animated:YES completion:nil];

    话虽如此,您还需要确保在屏幕上显示来自当前视图控制器的警报。如果您只有一个视图控制器,这将正常工作,但如果您在根 vc(或 2 个或 10 个)之上提供了另一个视图控制器,您将希望获得该提供的 vc 并拥有该 vc警报。

    这是一个例子:

    + (UIViewController*)getActiveViewController
    {
        UIViewController* vc = [[UIApplication sharedApplication] delegate].window.rootViewController;
        while(vc.presentedViewController)
        {
            vc = vc.presentedViewController;
        }
    
        return vc;
    }
    

    【讨论】:

    • Arg!我在原始帖子中缺少“viewController”(但在我的代码中没有)。我编辑了帖子以正确显示“[viewController presetViewController:alert animated:YES completion:nil];”这就是生成“No visible @interface ...”编译器错误的代码。我还尝试使用您的 while() 来获取顶级 vc,并且该 vc 会产生相同的消息(尽管感谢 while() 循环建议,大卫)。
    • 有“presetViewController”而不是“presentViewController”。谢谢,大卫。
    • 啊,是的。我修好了。抱歉打错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多