How to present UIAlertController when not in a view controller?

前端 未结 30 3586
庸人自扰
庸人自扰 2020-11-22 06:21

Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method call

30条回答
  •  梦如初夏
    2020-11-22 06:52

    The following solution did not work even though it looked quite promising with all the versions. This solution is generating WARNING.

    Warning: Attempt to present on whose view is not in the window hierarchy!

    https://stackoverflow.com/a/34487871/2369867 => This is looked promising then. But it was not in Swift 3. So I am answering this in Swift 3 and this is not template example.

    This is rather fully functional code by itself once you paste inside any function.

    Quick Swift 3 self-contained code

    let alertController = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.cancel, handler: nil))
    
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1;
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)
    

    This is tested and working code in Swift 3.

提交回复
热议问题