Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Created June 23, 2022 06:20
Show Gist options
  • Save magnuskahr/bf3063199ab73e5b96e24b882db38bc7 to your computer and use it in GitHub Desktop.
Save magnuskahr/bf3063199ab73e5b96e24b882db38bc7 to your computer and use it in GitHub Desktop.
extension View {
func fullscreenOverlay<Overlay: View>(isPresented show: Binding<Bool>, @ViewBuilder overlay: () -> Overlay) -> some View {
background {
FullscreenOverlayPresenter(show: show, overlay: overlay())
}
}
}
struct FullscreenOverlayPresenter<Overlay: View>: UIViewControllerRepresentable {
@Binding var show: Bool
let overlay: Overlay
@State private var presentedViewController: UIHostingController<Overlay>?
private var isShowing: Bool { presentedViewController != nil }
func makeUIViewController(context: Context) -> some UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
if show && !isShowing {
let toBePresented = UIHostingController(rootView: overlay)
toBePresented.view.backgroundColor = UIColor(white: 0, alpha: 0.3)
toBePresented.modalTransitionStyle = .crossDissolve
toBePresented.modalPresentationStyle = .overFullScreen
uiViewController.present(toBePresented, animated: true)
DispatchQueue.main.async {
presentedViewController = toBePresented
}
}
if !show, let presented = presentedViewController {
presented.dismiss(animated: true) {
DispatchQueue.main.async {
presentedViewController = nil
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment