简体   繁体   English

无法在 Swift 中从 UIView 显示 AlertController

[英]Unable to present AlertController from a UIView in Swift

I am trying to display an AlertController in Swift, but not from a UIViewController, but from a UIView that is called from its parent UIViewController.我试图在 Swift 中显示一个 AlertController,但不是来自 UIViewController,而是来自从其父 UIViewController 调用的 UIView。 When I try to call the controller, I am getting the following error:当我尝试调用控制器时,出现以下错误:

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

The code that I have which is trying to call the alertController is this:我试图调用 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);
            }
        }

The commented line in the above block of code is what the original block of code came with, and the line below the comment is the code I tried to replace it with.上面代码块中的注释行是原始代码块附带的行,注释下方的行是我尝试替换的代码。 Can anyone see what it is I'm doing wrong?谁能看到我做错了什么?

Is the root view controller already presenting a view controller?根视图控制器是否已经呈现视图控制器? If so, you may need to use:如果是这样,您可能需要使用:

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

Having said that, it might be easier (and more consistent/appropriate) to use a delegate pattern and let the view tell whatever view controller is managing it to present the alert view controller.话虽如此,使用委托模式并让视图告诉正在管理它的任何视图控制器来呈现警报视图控制器可能更容易(并且更一致/更合适)。

In Swift 5在斯威夫特 5

let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first

window?.rootViewController?.presentedViewController?.present(alert, animated: true, completion: nil)

快速 5 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM