I have a second UIWindow I'm adding to my app. When I add it the window briefly shows and then suddenly disappears. It might show for a tenth of a second then poof it's gone. Where am I going wrong at?
class AddSecondWindowClass: NSObject {
let redVC = RedController()
var window: UIWindow?
func showSecondWindow() {
let navVC = UINavigationController(rootViewController: redVC)
navVC.navigationBar.isHidden = true
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = .white
window?.windowLevel = UIWindowLevelStatusBar
window?.rootViewController = navVC
window?.isHidden = false
window?.makeKeyAndVisible()
}
}
class RedController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
}
deinit {
print("RedVC -DEINIT")
}
}
A different class with a button that shows the window
@IBAction func triggerSecondWindowButton(_ sender: UIButton) {
let addSecondWindowClass = AddSecondWindowClass()
addSecondWindowClass.showSecondWindow()
}
The problem is that you are not keeping the AddSecondWindowClass
object around.
You create a variable in the triggerSecondWindowButton(sender:)
method, but as soon as the function completes, addSecondWindowClass
has no more references to it and is soon destroyed. When this object is destroyed, your window you added has no more references so is also destroyed.
To solve this, you just have to keep a reference to the AddSecondWindowClass
somewhere it will be kept around for as long as you want the window to be visible. (Perhaps as a property or ivar in the class triggerSecondWindowButton(sender:)
is in).