如何从 Swift 中的 UIApplication 中删除 windows

How to Remove windows from UIApplication in Swift

点击按钮时,我正在使用以下代码移动到另一个视图控制器。

var window: UIWindow?
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.autoresizesSubviews = true
window?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let trackingViewController = LoginCameraViewController.init(screen: 
.main)
window?.rootViewController = trackingViewController
window?.addSubview((trackingViewController?.view)!)
window?.makeKeyAndVisible()
window?.layoutSubviews()

每点击一次按钮,都会添加一个新的 window 到 application.I 要删除的最新添加的 window。 使用以下代码可以知道应用程序中存在的 windows 个数。

let windowz = UIApplication.shared.windows
print("subviews",windowz)

我认为您在 iOS 中理解错误的导航概念。 Window 就像一个根对象,其中出现了 ViewController。因此,您首先要寻找的解决方案可能是 UINavigationController

Apple Documentation on Navigation

您应该使用 View Controller 而不是添加 windows 并在您要删除 window 的地方弹出它。 Window 只是应用程序的一个对象,将包含视图。 请纠正你的理解并使用视图控制器。

在下面的代码窗口中z是普通数组。

let windowz = UIApplication.shared.windows 

您可以使用

删除最后一个
windowz.removeLast()

For iOS 13 i was able to do it this way

我创建了包含 window 的数组,新的 viewController 使用它来呈现,

var arrWindow = [UIWindow]()
arrWindow.append(yourNewWindow)

// Note: This will be stored as strong reference so need to remove it.

还将您的原始 window 存储在变量

let originalWindow = yourOriginalWindow

// Note: Same goes for this as well ,this will be stored as strong reference so need to remove it.

删除的时候有很多方法,但这是最适合我的方法,

 func removeAppendedWindow() {

     for window in arrWindow {
         if window != originalWindow {
              if let index = arrWindow.index(of: window) {
                  window.isHidden = true
                  arrWindow.remove(at: index)
              }
         }
     }
}