【问题标题】:Issue while showing alert on window?在窗口上显示警报时出现问题?
【发布时间】:2018-03-27 06:29:42
【问题描述】:

我正在从下面的代码中设置我的应用程序的根视图控制器

let navController = UINavigationController()
    //App Theming
    navController.navigationBar.barTintColor = Constant.AppColor.navigationColor
    navController.navigationBar.tintColor = Constant.AppColor.navigationBarTintColor
    navController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: Constant.AppColor.navigationColorTextColor]
    navController.pushViewController(viewContoller, animated: true)
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = navController
    appDelegate.window?.makeKeyAndVisible()

现在,在我将一个控制器设置为 root 之后。然后我从下面的代码在窗口上显示警报。

    let window = UIApplication.shared.keyWindow!
     window.addSubView(mainView)

但是警报没有出现。请让我知道是什么问题?我无法理解。

编辑: 在应用程序启动时,我在应用程序后台线程中调用 api,因此我得到会话过期 & 在会话过期时,我向用户显示警报。因此,当显示警报和新控制器时,如果导航它会隐藏警报,因为新控制器已装箱。之后我尝试显示警报然后它不起作用

【问题讨论】:

标签: ios swift xcode


【解决方案1】:

不要使用window.addSubView(mainView) 来显示警报。

使用管理 mainView 的 viewController 并从 rootViewController 呈现它。

请参阅https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/PresentingaViewController.html,了解如何呈现 viewController

【讨论】:

  • 我已经为此创建了一个自定义类,所以我无法获取当前的控制器对象
  • 您想显示来自自定义类的警报?这已经讨论过几次了。 (例如stackoverflow.com/questions/36155769/…
  • 为什么每次显示警报时都需要创建一个新的 UIWindow() 对象。我可以为此使用 appdelegate 窗口
  • 通常视图控制器会显示警报,您可以在那里使用 present 方法。但是如果你所在的类不是 ViewController 或者没有对 ViewController 的引用,事情就复杂了。
  • 我无法更改在视图控制器上显示警报的方法,因为到目前为止我的代码已经达到了
【解决方案2】:

首先像这样添加根viewcontroller,然后在您的视图控制器中为viewdidappear添加警报代码

let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let object  = storyboard.instantiateViewController(withIdentifier:"yourViewController") as! yourViewController            
let addNavi = UINavigationController(rootViewController: object)            

self.window?.rootViewController = addNavi self.window?.makeKeyAndVisible()

【讨论】:

  • `DispatchQueue.main.async { // 添加警报代码 }`
【解决方案3】:

您不能在UIwindowUINavigationControllerUItabbarController 上显示任何警报,因为这些都指示给 root。

您需要显示在任何UIViewcontroller 对象上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2013-08-27
    相关资源
    最近更新 更多