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

后端 未结 8 992
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-12 03:55

In Objective-C in the viewDidLoad method of a UIViewController I do this to get the keyWindow reference in my iOS app:

 UIWindow * keyWindow = [[UIApplication sh         


        
相关标签:
8条回答
  • 2021-02-12 04:01

    Updating superarts.org's answer for Swift 3:

    if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window { 
          MBProgressHUD.show(text, view: window)
    }
    
    0 讨论(0)
  • 2021-02-12 04:03

    For Swift 5:

    var keyWindow: UIWindow? {
        return UIApplication.shared.connectedScenes.filter({$0.activationState == .foregroundActive}).map({$0 as? UIWindowScene}).compactMap({$0}).first?.windows.filter({$0.isKeyWindow}).first
    }
    
    0 讨论(0)
  • 2021-02-12 04:07

    The key window must not yet be set at the time of viewDidLoad. Your code works fine in viewDidAppear. Alternately, you can get the windows array in viewDidLoad, and get one (if there's more than one) of the windows from that array.

    0 讨论(0)
  • 2021-02-12 04:11

    The easiest way to do that is:

    in Objective-C

    [UIApplication sharedApplication].windows.firstObject
    

    in Swift

    UIApplication.shared.windows.first!
    

    Note that this works only if you do not support multiple windows.

    0 讨论(0)
  • 2021-02-12 04:18

    Swift 4 simply has UIApplication.shared.keyWindow property, no casting necessary.

    Note that iOS 13/iPadOS introduces UIScenes and explicit support for multiple windows, and thus deprecates the concept of keyWindow as it is no longer valid.

    This question has an overview how to get access to scene based windows.

    0 讨论(0)
  • 2021-02-12 04:21

    I came to this question when I was searching for getting window in swift. If you want to get window instead of keyWindow, try this:

    if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {
        MBProgressHUD.show(text, view:window)
    }
    

    Updated for Swift 3: (Thanks @Trevor)

    if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
        MBProgressHUD.show(text, view:window)
    }
    
    0 讨论(0)
提交回复
热议问题