How to present UIAlertController when not in a view controller?

前端 未结 30 3584
庸人自扰
庸人自扰 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 07:06

    This works in Swift for normal view controllers and even if there is a navigation controller on the screen:

    let alert = UIAlertController(...)
    
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1;
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController?.presentViewController(alert, animated: true, completion: nil)
    

提交回复
热议问题