Nazmul Hasan
Nazmul Hasan

Reputation: 10610

iOS access main window

How to access main window try this one but it is not working for me :

if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
 window.addSubview(offerView)
}

also i try with this way but no luck for me :

 if let window =  UIApplication.shared.windows.first {

       window.addSubview(offerView)
 }

Note: keyWindow work for me but Using keyWindow can return a keyboard or UIAlertView window, which lie above my application window.

Here is existing question i found but that answer not working for me

How do I get the keyWindow reference in a swift app?

on my application one offer view appear from bottom of the page. that offer will be shown half of the screen

Upvotes: 0

Views: 1509

Answers (2)

Hodson
Hodson

Reputation: 3556

let appDelegate = UIApplication.shared.delegate as? AppDelegate
let rootViewController = appDelegate?.window?.rootViewController

You can also cast the rootViewController if its a custom class i.e.

let rootViewController = appDelegate?.window?.rootViewController as? YourCustomViewController

Upvotes: 1

Aravind A R
Aravind A R

Reputation: 2714

The easiest solution will be to add a property variable window of type UIWindow in AppDelegate and adding rootviewcontroller to that window property and accessing that window property wherever you need.

Upvotes: 0

Related Questions