【问题标题】:Presenting Alert Controller from the delegate从委托人那里展示警报控制器
【发布时间】:2021-03-12 00:40:01
【问题描述】:

question/answer 的上下文中,我已经尝试过,但结果是没有显示警报。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    
    let alertController = UIAlertController(title: "Error", message: "ABc", preferredStyle: UIAlertController.Style.alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
    
    let win = UIWindow(frame: UIScreen.main.bounds)
    let vc = UIViewController()
    vc.view.backgroundColor = .clear
    win.rootViewController = vc
    win.windowLevel = UIWindow.Level.alert + 1  // Swift 3-4: UIWindowLevelAlert + 1
    win.makeKeyAndVisible()
    vc.present(alertController, animated: true, completion: nil)

    return true
}

根据答案尝试 2。

【问题讨论】:

  • 我不明白为什么UIWindow 需要参与。
  • 为什么要在 AppDelegate 中显示警报?!
  • 我在应用程序加载之前运行了一些与启动前相关的东西,如果出现任何问题,我需要提供一条警报消息。有什么解决办法吗?
  • 解决方案是在加载后在第一个视图控制器中呈现。
  • @cora code sn-p 请,我尝试了下面的答案,但 self.window 开头为零

标签: ios swift


【解决方案1】:

使用以下行:

self.window?.rootViewController?.present(alertController, animated: true, completion: nil)

代替

vc.present(alertController, animated: true, completion: nil)

问题解决了。

示例:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
        let alertController = UIAlertController(title: "Alert Title", message:
          "Message", preferredStyle: .actionSheet)

        let okAction = UIAlertAction(title: "Ok", style:.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }

        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
    })

【讨论】:

  • self.windowdidFinishLaunchingWithOptions 方法中为零
  • 您好,您可以尝试一下您的答案并发布一个工作示例吗?
  • @AppDeveloper 请查看我的更新答案
  • 不行,i.stack.imgur.com/i5raz.png,你也有编译错误,请测试代码。
  • 抱歉,nops,i.stack.imgur.com/GpnGV.png 也增加了延迟,我在我的应用程序中使用导航控制器作为初始视图控制器,有区别吗?你能把你的截图贴出来吗?
猜你喜欢
  • 1970-01-01
  • 2018-03-14
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多