How to present UIAlertController when not in a view controller?

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

    I posted a similar question a couple months ago and think I've finally solved the problem. Follow the link at the bottom of my post if you just want to see the code.

    The solution is to use an additional UIWindow.

    When you want to display your UIAlertController:

    1. Make your window the key and visible window (window.makeKeyAndVisible())
    2. Just use a plain UIViewController instance as the rootViewController of the new window. (window.rootViewController = UIViewController())
    3. Present your UIAlertController on your window's rootViewController

    A couple things to note:

    • Your UIWindow must be strongly referenced. If it's not strongly referenced it will never appear (because it is released). I recommend using a property, but I've also had success with an associated object.
    • To ensure that the window appears above everything else (including system UIAlertControllers), I set the windowLevel. (window.windowLevel = UIWindowLevelAlert + 1)

    Lastly, I have a completed implementation if you just want to look at that.

    https://github.com/dbettermann/DBAlertController

提交回复
热议问题