Skip to content

Instantly share code, notes, and snippets.

@ajjames
Created April 24, 2025 17:36
Show Gist options
  • Save ajjames/939792be09a0342e25175daf92f1d825 to your computer and use it in GitHub Desktop.
Save ajjames/939792be09a0342e25175daf92f1d825 to your computer and use it in GitHub Desktop.
FullScreenPresenter modifier
import SwiftUI
import UIKit
struct FullScreenPresenter<Overlay: View>: UIViewControllerRepresentable {
@Binding var isPresented: Bool
let overlay: () -> Overlay
func makeUIViewController(context: Context) -> UIViewController {
UIViewController() // container
}
func updateUIViewController(_ host: UIViewController, context: Context) {
if isPresented && context.coordinator.presented == nil {
let vc = UIHostingController(rootView: overlay())
vc.modalPresentationStyle = .overFullScreen
vc.modalTransitionStyle = .crossDissolve
context.coordinator.presented = vc
host.present(vc, animated: true)
}
else if !isPresented, let vc = context.coordinator.presented {
vc.dismiss(animated: true) {
context.coordinator.presented = nil
}
}
}
func makeCoordinator() -> Coordinator { Coordinator() }
class Coordinator { var presented: UIViewController? }
}
extension View {
/// Usage: .fullScreenOverlay(isPresented: $show) { MyOverlay() }
func fullScreenOverlay<Overlay: View>(
isPresented: Binding<Bool>,
@ViewBuilder _ overlay: @escaping () -> Overlay
) -> some View {
background( // attach it anywhere
FullScreenPresenter(isPresented: isPresented, overlay: overlay)
.frame(width: 0, height: 0)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment