Created
April 24, 2025 17:36
-
-
Save ajjames/939792be09a0342e25175daf92f1d825 to your computer and use it in GitHub Desktop.
FullScreenPresenter modifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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