How to present UIAlertController when not in a view controller?

前端 未结 30 3125
庸人自扰
庸人自扰 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:56

    Cross post my answer since these two threads are not flagged as dupes...

    Now that UIViewController is part of the responder chain, you can do something like this:

    if let vc = self.nextResponder()?.targetForAction(#selector(UIViewController.presentViewController(_:animated:completion:)), withSender: self) as? UIViewController {
    
        let alert = UIAlertController(title: "A snappy title", message: "Something bad happened", preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    
        vc.presentViewController(alert, animated: true, completion: nil)
    }
    

提交回复
热议问题