我试图在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);
}
}
上面代码块中的注释行是原始代码块附带的内容,注释下面的行是我试图替换它的代码。谁能看到我做错了什么?
答案 0 :(得分:6)
根视图控制器是否已经呈现视图控制器?如果是这样,您可能需要使用:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController?.presentViewController(alert, animated: true, completion: nil)
话虽如此,使用委托模式并让视图告诉控制器正在管理它以呈现警报视图控制器可能更容易(也更一致/更合适)。
答案 1 :(得分:0)
在Swift 5中
client.guilds.array().sort()
答案 2 :(得分:0)
快速5:
UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.present(alertName, animated: true, completion: nil)