【问题标题】:in iOS 13 [UIApplication sharedApplication] delegate].window does not work using objective-c在 iOS 13 [UIApplication sharedApplication] delegate].window 中使用objective-c 不起作用
【发布时间】:2020-02-03 16:11:11
【问题描述】:

我需要使用 Objective-c 显示来自非 UIView 类的警报。

下面是代码:

 UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@“Sample” message message:@“hello message” preferredStyle:UIAlertControllerStyleAlert];

[alertVC addAction:[UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}]];

[[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:alertVC animated:YES completion:nil];

上面的这个不再起作用了,我无法在objective-c中找到相同代码的任何其他替代方案。 我遇到了这个链接How to resolve: 'keyWindow' was deprecated in iOS 13.0,但解决方案是在 Swift 中,而不是在 Objective-c 中。

谢谢

【问题讨论】:

  • 在目标 c 中尝试相同的单词

标签: objective-c ios13 uialertcontroller uiwindow


【解决方案1】:

问题是在 iOS 13 中,这个表达式...

[[UIApplication sharedApplication] delegate].window.rootViewController

...是nil。这是因为 window 属性属于 scene 委托,而不是 app 委托。您最好通过 UIApplication 本身来访问窗口。例如,查看应用程序的窗口并找到关键的窗口。

【讨论】:

【解决方案2】:

您试图在键窗口中显示视图控制器,这将产生异常。试试这个代码

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

【讨论】:

    【解决方案3】:

    我认为在您的情况下,最简单的方法是使用以下代码替换您的最后一个代码行

    [UIApplication.sharedApplication.windows.lastObject.rootViewController 
        presentViewController:alertVC animated:YES completion:nil];
    

    【讨论】:

    • @sia,我的附加回答是会改变什么吗? )) ...给它一个机会 - 试试吧!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2020-02-18
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多