17
Nov
2020
Getting key window and top/root View Controller in SwiftUI
swiftui window viewcontroller keyboard rootReading time: 1 min
Here's a quick recipe for getting the key window, top or root View Controller, in a scene-based SwiftUI app.
extension UIApplication {
var currentKeyWindow: UIWindow? {
UIApplication.shared.connectedScenes
.filter { $0.activationState == .foregroundActive }
.map { $0 as? UIWindowScene }
.compactMap { $0 }
.first?.windows
.filter { $0.isKeyWindow }
.first
}
var rootViewController: UIViewController? {
currentKeyWindow?.rootViewController
}
var visibleViewController: UIViewController? {
currentKeyWindow?.visibleViewController
}
}
Search our recipes
Related Posts
- 100 Remove List Separator in SwiftUI (All Versions)
- 100 Prevent keyboard from covering up your text fields
- 100 SwiftUI Marquee
- 100 SwiftUI Segues
- 100 SwiftUI View to Image With ImageRenderer (Any Version)
Check out the companion apps!
Our free companion app and XCode Extension brings 100+ SwiftUI recipes right at your fingertips! Get a preview of it in the Online Companion.
Have a recipe for us?
Get in touch and let's grow the cookbook together!