ios - 无论视图层次结构如何,都将UIAlertController呈现在所有内容之上

Gui*_*uig 33 crash popup ios swift

我正在尝试提供一个帮助类UIAlertController.因为它是一个帮助类,所以我希望它不管视图层次结构如何工作,并且没有关于它的信息.我能够显示警报,但当它被解雇时,应用程序崩溃了:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Trying to dismiss UIAlertController <UIAlertController: 0x135d70d80>
 with unknown presenter.'
Run Code Online (Sandbox Code Playgroud)

我正在创建弹出窗口:

guard let window = UIApplication.shared.keyWindow else { return }
let view = UIView()
view.isUserInteractionEnabled = true
window.insertSubview(view, at: 0)
window.bringSubview(toFront: view)
// add full screen constraints to view ...

let controller = UIAlertController(
  title: "confirm deletion?",
  message: ":)",
  preferredStyle: .alert
)

let deleteAction = UIAlertAction(
  title: "yes",
  style: .destructive,
  handler: { _ in
    DispatchQueue.main.async {
      view.removeFromSuperview()
      completion()
    }
  }
)
controller.addAction(deleteAction)

view.insertSubview(controller.view, at: 0)
view.bringSubview(toFront: controller.view)
// add centering constraints to controller.view ...
Run Code Online (Sandbox Code Playgroud)

当我点击时yes,应用程序将崩溃并且在崩溃之前没有命中处理程序.我无法呈现,UIAlertController因为这将取决于当前的视图层次结构,而我希望弹出窗口是独立的

编辑:Swift解决方案感谢@Vlad的想法.看起来在单独的窗口中操作要简单得多.所以这是一个有效的Swift解决方案:

class Popup {
  private var alertWindow: UIWindow
  static var shared = Popup()

  init() {
    alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1
    alertWindow.makeKeyAndVisible()
    alertWindow.isHidden = true
  }

  private func show(completion: @escaping ((Bool) -> Void)) {
    let controller = UIAlertController(
      title: "Want to do it?",
      message: "message",
      preferredStyle: .alert
    )

    let yesAction = UIAlertAction(
      title: "Yes",
      style: .default,
      handler: { _ in
        DispatchQueue.main.async {
          self.alertWindow.isHidden = true
          completion(true)
        }
    })

    let noAction = UIAlertAction(
      title: "Not now",
      style: .destructive,
      handler: { _ in
        DispatchQueue.main.async {
          self.alertWindow.isHidden = true
          completion(false)
        }
    })

    controller.addAction(noAction)
    controller.addAction(yesAction)
    self.alertWindow.isHidden = false
    alertWindow.rootViewController?.present(controller, animated: false)
  }
}
Run Code Online (Sandbox Code Playgroud)

jaz*_*gil 86

这是一个Swift 3扩展:

public extension UIAlertController {
    func show() {
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindow.Level.alert + 1  // Swift 3-4: UIWindowLevelAlert + 1
        win.makeKeyAndVisible()    
        vc.present(self, animated: true, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

只需设置你的UIAlertController,然后调用:

alert.show()
Run Code Online (Sandbox Code Playgroud)

不再受View Controllers层次结构的约束!

  • 那么你怎么会隐藏它呢? (12认同)
  • 这在iOS 13.0中停止工作 (8认同)
  • 真的,这很完美。好一个 (2认同)
  • 在Xcode 11和iOS 13 Beta中,此答案(我使用了很长时间)使警报显示,然后在大约0.5秒内消失。任何人都在新Beta中有足够的时间知道为什么吗? (2认同)

Vla*_*tko 15

我宁愿把它呈现在UIApplication.shared.keyWindow.rootViewController上,而不是使用你的逻辑.所以你可以做下一个:

UIApplication.shared.keyWindow.rootViewController.presentController(yourAlert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

编辑:

我有一个旧的ObjC类别,我使用了下一个方法show,我使用过,如果没有提供控制器来呈现:

- (void)show
{
    self.alertWindow = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
    self.alertWindow.rootViewController = [UIViewController new];
    self.alertWindow.windowLevel = UIWindowLevelAlert + 1;
    [self.alertWindow makeKeyAndVisible];
    [self.alertWindow.rootViewController presentViewController: self animated: YES completion: nil];
}
Run Code Online (Sandbox Code Playgroud)

添加整个类别,如果有人需要它

#import "UIAlertController+ShortMessage.h"
#import <objc/runtime.h>

@interface UIAlertController ()
@property (nonatomic, strong) UIWindow* alertWindow;
@end

@implementation UIAlertController (ShortMessage)

- (void)setAlertWindow: (UIWindow*)alertWindow
{
    objc_setAssociatedObject(self, @selector(alertWindow), alertWindow, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIWindow*)alertWindow
{
    return objc_getAssociatedObject(self, @selector(alertWindow));
}

+ (UIAlertController*)showShortMessage: (NSString*)message fromController: (UIViewController*)controller
{
    return [self showAlertWithTitle: nil shortMessage: message fromController: controller];
}

+ (UIAlertController*)showAlertWithTitle: (NSString*)title shortMessage: (NSString*)message fromController: (UIViewController*)controller
{
    return [self showAlertWithTitle: title shortMessage: message actions: @[[UIAlertAction actionWithTitle: @"Ok" style: UIAlertActionStyleDefault handler: nil]] fromController: controller];
}

+ (UIAlertController*)showAlertWithTitle: (NSString*)title shortMessage: (NSString*)message actions: (NSArray<UIAlertAction*>*)actions fromController: (UIViewController*)controller
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle: title
                                                    message: message
                                             preferredStyle: UIAlertControllerStyleAlert];

    for (UIAlertAction* action in actions)
    {
        [alert addAction: action];
    }

    if (controller)
    {
        [controller presentViewController: alert animated: YES completion: nil];
    }
    else
    {
        [alert show];
    }

    return alert;
}

+ (UIAlertController*)showAlertWithMessage: (NSString*)message actions: (NSArray<UIAlertAction*>*)actions fromController: (UIViewController*)controller
{
    return [self showAlertWithTitle: @"" shortMessage: message actions: actions fromController: controller];
}

- (void)show
{
    self.alertWindow = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
    self.alertWindow.rootViewController = [UIViewController new];
    self.alertWindow.windowLevel = UIWindowLevelAlert + 1;
    [self.alertWindow makeKeyAndVisible];
    [self.alertWindow.rootViewController presentViewController: self animated: YES completion: nil];
}

@end
Run Code Online (Sandbox Code Playgroud)

  • 如果您有一个以模式模式呈现的 viewController,那么您的代码将不会在其前面显示 UIAlertController。 (4认同)

iOS*_*iOS 8

在Swift 4.1和Xcode 9.4.1中

我正在从我的共享课程调用警报功能

//This is my shared class
import UIKit

class SharedClass: NSObject {

static let sharedInstance = SharedClass()
    //This is alert function
    func alertWindow(title: String, message: String) {
        let alertWindow = UIWindow(frame: UIScreen.main.bounds)
        alertWindow.rootViewController = UIViewController()
        alertWindow.windowLevel = UIWindowLevelAlert + 1

        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert2.addAction(defaultAction2)

        alertWindow.makeKeyAndVisible()
        alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
    }
    private override init() {
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在我所需的视图控制器中调用此警报功能.

//I'm calling this function into my second view controller
SharedClass.sharedInstance.alertWindow(title:"Title message here", message:"Description message here")
Run Code Online (Sandbox Code Playgroud)


Max*_*hun 8

具有添加show()方法和本地实例的旧方法UIWindow在iOS 13上不再起作用(立即关闭窗口)。

这是应该在iOS 13上运行的UIAlertController Swift扩展:

import UIKit

private var associationKey: UInt8 = 0

extension UIAlertController {

    private var alertWindow: UIWindow! {
        get {
            return objc_getAssociatedObject(self, &associationKey) as? UIWindow
        }

        set(newValue) {
            objc_setAssociatedObject(self, &associationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }

    func show() {
        self.alertWindow = UIWindow.init(frame: UIScreen.main.bounds)
        self.alertWindow.backgroundColor = .red

        let viewController = UIViewController()
        viewController.view.backgroundColor = .green
        self.alertWindow.rootViewController = viewController

        let topWindow = UIApplication.shared.windows.last
        if let topWindow = topWindow {
            self.alertWindow.windowLevel = topWindow.windowLevel + 1
        }

        self.alertWindow.makeKeyAndVisible()
        self.alertWindow.rootViewController?.present(self, animated: true, completion: nil)
    }

    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        self.alertWindow.isHidden = true
        self.alertWindow = nil
    }
}
Run Code Online (Sandbox Code Playgroud)

这样UIAlertController就可以创建并显示如下:

let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Title", style: .default) { (action) in
    print("Action")
}

alertController.addAction(alertAction)
alertController.show()
Run Code Online (Sandbox Code Playgroud)

  • 我想警告您这个解决方案。当扩展覆盖 viewDidDisappear 时,如果您没有使用 show() 方法来呈现,这会导致崩溃! (2认同)
  • 通过将alertWindow转换为可选值,或将断言添加到viewDidDisappear(以便开发人员了解必须事先调用show()方法),可以轻松解决此问题。我的建议是:在使用 API 之前确保您了解 API 的工作原理:) (2认同)