Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstrates an approach for dismissing a SwiftUI view presented via a UIHostingController
struct SwiftUIView: View {
@ObservedObject var delegate: SheetDismisser
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button(action: {
self.presentationMode.wrappedValue.dismiss() // SwiftUI
self.delegate.dismiss() // UIKit
}) {
Text("Dismiss")
}
}
}
import SwiftUI
private final class SheetDismisser: ObservableObject {
fileprivate weak var host: ViewController?
func dismiss() {
host?.dismiss(animated: true)
}
}
final class ViewController: UIHostingController<AnyView> {
deinit { dismissHandler() }
var dismissHandler: () -> Void
init(dismissHandler: @escaping () -> Void) {
self.dismissHandler = dismissHandler
let delegate = SheetDismisser()
let view = SwiftUIView(delegate: delegate)
super.init(rootView: AnyView(view))
delegate.host = self
}
@objc required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
@shaps80

This comment has been minimized.

Copy link
Owner Author

@shaps80 shaps80 commented Feb 10, 2021

Terribly named and undocumented – apologies for that.

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