【问题标题】:Unable to present AlertController from a UIView in Swift无法从 Swift 中的 UIView 呈现 AlertController
【发布时间】:2016-06-09 16:19:28
【问题描述】:

我试图在 Swift 中显示一个 AlertController,但不是来自 UIViewController,而是来自从其父 UIViewController 调用的 UIView。当我尝试调用控制器时,出现以下错误:

Warning: Attempt to present <UIAlertController: 0x7fa5544a3140> on
<UINavigationController: 0x7fa553830400> whose view is not in the window
hierarchy!

我尝试调用 alertController 的代码是这样的:

let logInButton = TWTRLogInButton { (session, error) in
            if let unwrappedSession = session {
                let alert = UIAlertController(title: "Logged In",
                    message: "User \(unwrappedSession.userName) has logged in",
                    preferredStyle: UIAlertControllerStyle.Alert
                )
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                //self.presentViewController(alert, animated: true, completion: nil)
                UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
            } else {
                NSLog("Login error: %@", error!.localizedDescription);
            }
        }

上面代码块中的注释行是原始代码块附带的,注释下面的行是我试图替换它的代码。谁能看到我做错了什么?

【问题讨论】:

    标签: ios swift uiview uialertcontroller


    【解决方案1】:

    根视图控制器是否已经呈现视图控制器?如果是这样,您可能需要使用:

    UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController?.presentViewController(alert, animated: true, completion: nil)
    

    话虽如此,使用委托模式可能更容易(并且更一致/合适)并让视图告诉任何视图控制器正在管理它以呈现警报视图控制器。

    【讨论】:

    • 非常感谢您的解决方案。虽然它确实有效,但我对您提到的委托解决方案感到好奇。你能再详细说明一下吗?
    • 您可以为您的视图创建一个委托protocol 并让您的视图控制器采用它。该协议将指定一个方法(例如,loginViewDidLoginSuccessfully(loginView: SomeLoginViewClass, withUsername username: String)。这与UITableViewUICollectionView 使用与UIViewController 通信的方法相同(SDK 中的许多其他组件使用相同的模式)。想象一下,如果您必须对选择单元格时发生的逻辑进行硬编码 - 这会使 UITableView 的可重用性大大降低。
    【解决方案2】:

    在 Swift 5 中

    let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
    
    window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)
    

    【讨论】:

      【解决方案3】:

      对于 Swift 5:

      UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.present(alertName, animated: true, completion: nil)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-10
        • 1970-01-01
        相关资源
        最近更新 更多