ios - 无论视图层次结构

时间:2016-12-06 09:03:38

标签: ios swift crash popup

我试图有一个提示UIAlertController的助手类。由于它是一个帮助类,我希望它能够工作而不管视图层次结构如何,并且没有关于它的信息。我能够显示警报,但当它被解雇时,该应用程序崩溃了:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Trying to dismiss UIAlertController <UIAlertController: 0x135d70d80>
 with unknown presenter.'

我用以下方法创建弹出窗口:

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 ...

当我点击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)
  }
}

12 个答案:

答案 0 :(得分:74)

这是一个Swift 3/4扩展名:

public extension UIAlertController {
    func show() {
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindowLevelAlert + 1
        win.makeKeyAndVisible()    
        vc.present(self, animated: true, completion: nil)
    }
}

对于Swift 5:

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
        win.makeKeyAndVisible()    
        vc.present(self, animated: true, completion: nil)
    }
}

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

alert.show()

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

答案 1 :(得分:13)

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

UIApplication.shared.keyWindow.rootViewController.presentController(yourAlert, animated: true, completion: nil)

编辑:

我有一个旧的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];
}
如果有人需要,

添加整个类别

#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

答案 2 :(得分:9)

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

这里是UIAlertController Swift扩展,它应在iOS 13上运行

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
    }
}

然后可以这样创建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()

答案 3 :(得分: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() {
    }
}

我正在像这样在所需的视图控制器中调用此警报功能。

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

答案 4 :(得分:4)

Swift 3 示例

let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1

let alert = UIAlertController(title: "AlertController Tutorial", message: "Submit something", preferredStyle: .alert)

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

答案 5 :(得分:3)

使用新创建的UIWindow作为UIAlertController扩展名的常用解决方案在iOS 13 Beta中停止工作(看来iOS不再对UIWindow拥有强大的引用,因此警报会立即消失)。

以下解决方案稍微复杂一些,但可以在iOS 13.0和更低版本的iOS中使用:

class GBViewController: UIViewController {
    var didDismiss: (() -> Void)?
    override func dismiss(animated flag: Bool, completion: (() -> Void)?)
    {
        super.dismiss(animated: flag, completion:completion)
        didDismiss?()
    }
    override var prefersStatusBarHidden: Bool {
        return true
    }
}

class GlobalPresenter {
    var globalWindow: UIWindow?
    static let shared = GlobalPresenter()

    private init() {
    }

    func present(controller: UIViewController) {
        globalWindow = UIWindow(frame: UIScreen.main.bounds)
        let root = GBViewController()
        root.didDismiss = {
            self.globalWindow?.resignKey()
            self.globalWindow = nil
        }
        globalWindow!.rootViewController = root
        globalWindow!.windowLevel = UIWindow.Level.alert + 1
        globalWindow!.makeKeyAndVisible()
        globalWindow!.rootViewController?.present(controller, animated: true, completion: nil)
    }
}

用法

    let alert = UIAlertController(title: "Alert Test", message: "Alert!", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    GlobalPresenter.shared.present(controller: alert)

答案 6 :(得分:3)

这通过结合Ruslan和Steve的答案在iOS 13.1和Xcode 11.5上对我有效。

func activeVC() -> UIViewController? {

let appDelegate = UIApplication.shared.delegate as! AppDelegate

var topController: UIViewController = appDelegate.window!.rootViewController!
while (topController.presentedViewController != nil) {
    topController = topController.presentedViewController!
}

return topController 
}

用法:

activeVC()?.present(alert, animated: true)

答案 7 :(得分:2)

如果您试图在以模态形式呈现的UIViewController中呈现UIActivityController,则需要从presentedViewController呈现。否则,什么也不会呈现。我在iOS 13中使用此方法返回活动的UIViewController:

_blank

例如,

func activeVC() -> UIViewController? {
    // Use connectedScenes to find the .foregroundActive rootViewController
    var rootVC: UIViewController?
    for scene in UIApplication.shared.connectedScenes {
        if scene.activationState == .foregroundActive {
            rootVC = (scene.delegate as? UIWindowSceneDelegate)?.window!!.rootViewController
            break
        }
    }
    // Then, find the topmost presentedVC from it.
    var presentedVC = rootVC
    while presentedVC?.presentedViewController != nil {
        presentedVC = presentedVC?.presentedViewController
    }
    return presentedVC
}

答案 8 :(得分:1)

 func windowErrorAlert(message:String){
    let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
    let window = UIWindow(frame: UIScreen.main.bounds)
    window.rootViewController = UIViewController()
    let okAction = UIAlertAction(title: "Ok", style: .default) { (action) -> Void in
        alert.dismiss(animated: true, completion: nil)
        window.resignKey()
        window.isHidden = true
        window.removeFromSuperview()
        window.windowLevel = UIWindowLevelAlert - 1
        window.setNeedsLayout()
    }

    alert.addAction(okAction)
    window.windowLevel = UIWindowLevelAlert + 1
    window.makeKeyAndVisible()

    window.rootViewController?.present(alert, animated: true, completion: nil)
}

在所有视图的基础上创建一个UIAlertController,同时将其关闭并重点放回rootViewController。

答案 9 :(得分:1)

TVOS 13和iOS 13的工作解决方案

static func showOverAnyVC(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: {(action) -> Void in
    })))
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    var topController: UIViewController = appDelegate.window!.rootViewController!
    while (topController.presentedViewController != nil) {
        topController = topController.presentedViewController!
    }

    topController.present(alert, animated: true, completion: nil)
}

答案 10 :(得分:1)

以下代码适用于iOS 13以及旧版本:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myVC = storyboard.instantiateViewController(withIdentifier: "MyVC") as! MyViewController
            
myVC.view.backgroundColor = .clear
myVC.modalPresentationStyle = .overCurrentContext
            
self.present(popup, animated: true, completion: nil)

答案 11 :(得分:0)

我自己的iOS 13解决方法。

我不是使用UIViewController的子类(Andreas解决方案)或添加关联的对象(Maxim解决方案),而是使用UIWindow的非常简单的子类,该子类在UIAlertController的类别(扩展)文件中声明:

@interface AlertWindow : UIWindow
@property (nonatomic) UIWindow *autoretain;
@end

@implementation AlertWindow
@end

然后在show方法中:

AlertWindow *win = [[AlertWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
win.autoretain = win;
… //code as usual

最后发布:

- (void)viewWillDisappear:(BOOL)animated {
    AlertWindow *win = (AlertWindow *)self.view.window;
    if ([win isKindOfClass:AlertWindow.class]) win.autoretain = nil;
    [super viewWillDisappear:animated];
}

我确实意识到OP标记了Swift,这就是ObjC,但这很容易适应……