Search code examples
iosswiftuiwindow

How to add UIView on the top of all views


I'm trying to set a subview on my application for all views, i want to use it for internet connection test.

I have tried adding it to UIWindow in appDelegate using this code

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
    [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let myNewView=UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 200))
    myNewView.backgroundColor=UIColor.red
    UIApplication.shared.keyWindow?.addSubview(myNewView)
}

when i run my app i don't find any changes , and the subview doesn't appear


Solution

  • Becasuse in didFinishLaunchingWithOptions this

    UIApplication.shared.keyWindow?
    

    is nil you can use

    self.window?.makeKeyAndVisible()
    self.window?.addSubview(.....
    

    After you init with correct window or guarantee a root vc from IB with storyboard entry