无法从Swift中的UIView呈现AlertController

sye*_*dfa 1 uiview ios swift uialertcontroller

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

Warning: Attempt to present <UIAlertController: 0x7fa5544a3140> on
<UINavigationController: 0x7fa553830400> whose view is not in the window
hierarchy!
Run Code Online (Sandbox Code Playgroud)

我试图调用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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

上面代码块中的注释行是原始代码块附带的内容,注释下面的行是我试图替换它的代码.任何人都可以看到它我做错了什么?

Cha*_* A. 7

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

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController?.presentViewController(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

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