UIWindow 未显示 iOS 13 中的内容

UIWindow not showing over content in iOS 13

我正在升级我的应用程序以使用 iOS 13 中定义的新 UIScene 模式,但是该应用程序的关键部分已停止工作。 我一直在使用 UIWindow 来覆盖屏幕上的当前内容并向用户呈现新信息,但在当前的测试版中我正在使用 (iOS + XCode beta 3) window 会出现,但会立即消失。

这是我使用的代码,现在不起作用:

let window = UIWindow(frame: UIScreen.main.bounds)
let viewController = UIViewController()
viewController.view.backgroundColor = .clear
window.rootViewController = viewController
window.windowLevel = UIWindow.Level.statusBar + 1
window.makeKeyAndVisible()
viewController.present(self, animated: true, completion: nil)

我已经尝试了很多方法,包括使用 WindowScenes 来展示新的 UIWindow,但找不到任何实际的文档或示例。

我的一次尝试(没有用 - 同样的行为 window 立即出现并消失)

let windowScene = UIApplication.shared.connectedScenes.first
if let windowScene = windowScene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    let viewController = UIViewController()
    viewController.view.backgroundColor = .clear
    window.rootViewController = viewController
    window.windowLevel = UIWindow.Level.statusBar + 1
    window.makeKeyAndVisible()
    viewController.present(self, animated: true, completion: nil)
}

在 iOS 13 beta 中有人能够做到这一点吗?

谢谢

编辑

从提出这个问题到 iOS 13 的最终版本发布已经过去了一段时间。下面有很多答案,但几乎所有答案都包含一件事——Adding a strong/stronger reference to the UIWindow。您可能需要包含一些与新场景相关的代码,但请先尝试添加强引用。

我在升级 iOS 13 场景模式的代码时遇到了同样的问题。使用您的第二个代码片段的部分内容,我设法修复了所有问题,因此我的 windows 再次出现了。除了最后一行,我和你做的一样。尝试删除 viewController.present(...)。这是我的代码:

let windowScene = UIApplication.shared
                .connectedScenes
                .filter { [=10=].activationState == .foregroundActive }
                .first
if let windowScene = windowScene as? UIWindowScene {
    popupWindow = UIWindow(windowScene: windowScene)
}

那我像你一样展示一下:

popupWindow?.frame = UIScreen.main.bounds
popupWindow?.backgroundColor = .clear
popupWindow?.windowLevel = UIWindow.Level.statusBar + 1
popupWindow?.rootViewController = self as? UIViewController
popupWindow?.makeKeyAndVisible()

反正我个人认为问题出在viewController.present(...),因为你用那个controller显示一个window,马上就出现一些'self',所以要看什么'self' 真的是。

另外值得一提的是,我存储了对 window 你从我的控制器中移动的引用。如果这对你仍然没用我只能展示我使用这个代码的小repo。查看 AnyPopupController.swiftPopup.swift 文件。

希望对您有所帮助,@SirOz

谢谢@glassomoss。我的问题是 UIAlertController。

我是这样解决问题的:

  • 我添加了一个变量
var windowsPopUp: UIWindow?
  • 我修改了显示弹出窗口的代码:
public extension UIAlertController {
    func showPopUp() {
        windowsPopUp = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        windowsPopUp!.rootViewController = vc
        windowsPopUp!.windowLevel = UIWindow.Level.alert + 1
        windowsPopUp!.makeKeyAndVisible()
        vc.present(self, animated: true)
    }
}
  • 在我添加的 UIAlertController 的动作中:
windowsPopUp = nil

没有最后一行,弹出窗口被关闭,但 windows 保持活动状态,不允许与应用程序迭代(与应用程序 window)

iOS 13 破坏了我管理警报的辅助功能。

因为在某些情况下,您可能需要同时显示多个警报(最近的警报高于旧警报),例如,如果您显示是或否警报,同时您的网络服务 returns 通过警报显示错误(这是一个极限情况,但它可能会发生),

我的解决方案是像这样扩展 UIAlertController,让它有自己的 alertWindow 来显示。

优点是,当您解除警报时,window 会自动解除,因为还剩下任何强引用,因此无需实施进一步的模组。

免责声明:我刚刚实现了它,所以我还需要看看它是否一致...

class AltoAlertController: UIAlertController {

var alertWindow : UIWindow!

func show(animated: Bool, completion: (()->(Void))?)
{
    alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindow.Level.alert + 1
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController?.present(self, animated: animated, completion: completion)
}

}

基于所有建议的解决方案,我可以提供我自己的代码版本:

private var window: UIWindow!

extension UIAlertController {
    func present(animated: Bool, completion: (() -> Void)?) {
        window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = UIViewController()
        window.windowLevel = .alert + 1
        window.makeKeyAndVisible()
        window.rootViewController?.present(self, animated: animated, completion: completion)
    }

    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        window = nil
    }
}

使用方法:

// Show message (from any place)
let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Button", style: .cancel))
alert.present(animated: true, completion: nil)

您只需要存储 strong 您想要展示的 UIWindow 的引用。似乎在显示的视图控制器下没有引用 window.

正如其他人所提到的,问题是需要对 window 的强引用。因此,为了确保这个 window 在使用后再次被删除,我将所有需要的东西封装在它自己的 class..

这里有一点 Swift 5 片段:

class DebugCheatSheet {

    private var window: UIWindow?

    func present() {
        let vc = UIViewController()
        vc.view.backgroundColor = .clear

        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = vc
        window?.windowLevel = UIWindow.Level.alert + 1
        window?.makeKeyAndVisible()

        vc.present(sheet(), animated: true, completion: nil)
    }

    private func sheet() -> UIAlertController {
        let alert = UIAlertController.init(title: "Cheatsheet", message: nil, preferredStyle: .actionSheet)
        addAction(title: "Ok", style: .default, to: alert) {
            print("Alright...")
        }
        addAction(title: "Cancel", style: .cancel, to: alert) {
            print("Cancel")
        }
        return alert
    }

    private func addAction(title: String?, style: UIAlertAction.Style, to alert: UIAlertController, action: @escaping () -> ()) {
        let action = UIAlertAction.init(title: title, style: style) { [weak self] _ in
            action()
            alert.dismiss(animated: true, completion: nil)
            self?.window = nil
        }
        alert.addAction(action)
    }
}

下面是我的使用方式。它来自整个应用程序视图层次结构中的最低视图控制器,但也可以在其他任何地方使用:

private let cheatSheet = DebugCheatSheet()

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        cheatSheet.present()
    }
}

这里有一个有点 hacky 的方法来保持对创建的 UIWindow 的强引用,并在呈现的视图控制器被关闭和释放后释放它。 只要确保你没有引用循环。

private final class WindowHoldingViewController: UIViewController {

    private var window: UIWindow?

    convenience init(window: UIWindow) {
        self.init()

        self.window = window
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.clear
    }

    override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
        let view = DeallocatingView()
        view.onDeinit = { [weak self] in
            self?.window = nil
        }
        viewControllerToPresent.view.addSubview(view)

        super.present(viewControllerToPresent, animated: flag, completion: completion)
    }

    private final class DeallocatingView: UIView {

        var onDeinit: (() -> Void)?

        deinit {
            onDeinit?()
        }
    }
}

用法:

let vcToPresent: UIViewController = ...
let window = UIWindow() // or create via window scene
...
window.rootViewController = WindowHoldingViewController(window: window)
...
window.rootViewController?.present(vcToPresent, animated: animated, completion: completion)

需要为 ios13 创建 window 指针。

例如我的代码:

 extension UIAlertController {

    private static var _aletrWindow: UIWindow?
    private static var aletrWindow: UIWindow {
        if let window = _aletrWindow {
            return window
        } else {
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = UIViewController()
            window.windowLevel = UIWindowLevelAlert + 1
            window.backgroundColor = .clear
            _aletrWindow = window
            return window
        }
    }

    func presentGlobally(animated: Bool, completion: (() -> Void)? = nil) {
        UIAlertController.aletrWindow.makeKeyAndVisible()
        UIAlertController.aletrWindow.rootViewController?.present(self, animated: animated, completion: completion)
    }

    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        UIAlertController.aletrWindow.isHidden = true
    }

}

使用:

let alert = UIAlertController(...
...

alert.presentGlobally(animated: true)

以下是在 iOS 13 上的新 window 中呈现视图控制器的步骤:

  1. 检测焦点UIWindowScene
extension UIWindowScene {
    static var focused: UIWindowScene? {
        return UIApplication.shared.connectedScenes
            .first { [=10=].activationState == .foregroundActive && [=10=] is UIWindowScene } as? UIWindowScene
    }
}
  1. 为焦点场景创建UIWindow
if let window = UIWindowScene.focused.map(UIWindow.init(windowScene:)) {
  // ...
}
  1. UIViewController在那window.
let myViewController = UIViewController()

if let window = UIWindowScene.focused.map(UIWindow.init(windowScene:)) {
    window.rootViewController = myViewController
    window.makeKeyAndVisible()
}

Swift 4.2 iOS 13 UIAlertController 扩展

此代码完全适用于 iOS 11、12 和 13

import Foundation
import UIKit

extension UIAlertController{
    private struct AssociatedKeys {
        static var alertWindow = "alertWindow"
    }
    var alertWindow:UIWindow?{
        get{
            guard let alertWindow = objc_getAssociatedObject(self, &AssociatedKeys.alertWindow) as? UIWindow else {
                return nil
            }
            return alertWindow
        }
        set(value){
            objc_setAssociatedObject(self,&AssociatedKeys.alertWindow,value,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func show(animated:Bool) {
        self.alertWindow = UIWindow(frame: UIScreen.main.bounds)
        self.alertWindow?.rootViewController = UIViewController()
        self.alertWindow?.windowLevel = UIWindow.Level.alert + 1
        if #available(iOS 13, *){
            let mySceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate
            mySceneDelegate!.window?.rootViewController?.present(self, animated: animated, completion: nil)
        }
        else{
            self.alertWindow?.makeKeyAndVisible()
            self.alertWindow?.rootViewController?.present(self, animated: animated, completion: nil)
        }
    }
}

你可以这样试试:

extension UIWindow {
    static var key: UIWindow? {
        if #available(iOS 13, *) {
            return UIApplication.shared.windows.first { [=10=].isKeyWindow }
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}

用法:

if let rootVC = UIWindow.key?.rootViewController {
    rootVC.present(nextViewController, animated: true, completion: nil)
}

继续编码.......... :)

除了有关创建对 UIWindow 的引用然后以模态方式呈现的答案外,我还包含了一段代码,说明我如何关闭它。

class PresentingViewController: UIViewController {
    private var coveringWindow: UIWindow?

  func presentMovie() {
    let playerVC = MoviePlayerViewController()
    playerVC.delegate = self
    playerVC.modalPresentationStyle = .overFullScreen
    playerVC.modalTransitionStyle = .coverVertical

    self.coverPortraitWindow(playerVC)
  }

  func coverPortraitWindow(_ movieController: MoviePlayerViewController) {

    let windowScene = UIApplication.shared
        .connectedScenes
        .filter { [=10=].activationState == .foregroundActive }
        .first
    if let windowScene = windowScene as? UIWindowScene {
        self.coveringWindow = UIWindow(windowScene: windowScene)

        let rootController = UIViewController()
        rootController.view.backgroundColor = .clear

        self.coveringWindow!.windowLevel = .alert + 1
        self.coveringWindow!.isHidden = false
        self.coveringWindow!.rootViewController = rootController
        self.coveringWindow!.makeKeyAndVisible()

        rootController.present(movieController, animated: true)
    }
  }

  func uncoverPortraitWindow() {
    guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
        let sceneDelegate = windowScene.delegate as? SceneDelegate
        else {
            return
    }
    sceneDelegate.window?.makeKeyAndVisible()
    self.coveringWindow = nil
  }

}