Skip to content

Instantly share code, notes, and snippets.

@vladdeSV
Last active February 14, 2024 09:56
Show Gist options
  • Save vladdeSV/42e418c4a01696d3622da4a640b4ab61 to your computer and use it in GitHub Desktop.
Save vladdeSV/42e418c4a01696d3622da4a640b4ab61 to your computer and use it in GitHub Desktop.
SwiftUI, get top view controller
//
// UIApplication+TopViewController.swift
// Ticketing & Sales
//
// Created by Vladimirs Nordholm on 2024-02-14.
//
import SwiftUI
extension UIApplication {
public var topViewController: UIViewController? {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let rootViewController = windowScene.windows.first?.rootViewController else {
return nil
}
var topViewController = rootViewController
while let presentedViewController = topViewController.presentedViewController {
topViewController = presentedViewController
}
return topViewController
}
}
@vladdeSV
Copy link
Author

usage: UIApplication.shared.topViewController

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment