To add a “close” button to a modal view we can use a dismiss closure provided by the ModalLink:
struct ContentView: View {
var body: some View {
ModalPresenter {
ModalLink(destination: { dismiss in
Button(action: dismiss) {
Text("Dismiss")
}
}) {
Text("Main view")
}
}
}
}
Moving the destination in the code above to a separate structure is a recommended way here to refactor the code here as modal views regularly contains a bit more that just a text or button.
struct ContentView: View {
var body: some View {
ModalPresenter {
ModalLink(destination: MyModalView.init(dismiss:)) {
Text("Main view")
}
}
}
}
struct MyModalView: View {
var dismiss: () -> ()
var body: some View {
Button(action: dismiss) {
Text("Dismiss")
}
}
}
ModalView
An analogue of SwiftUI
NavigationView
that provides a convenient interface of displaying modal views.How to use
Step 1
Add a dependency using Swift Package Manager to your project: https://github.com/diniska/modal-view
Step 2
Import the dependency
Step 3
Use
ModalPresenter
andModalLink
the same way you would useNavigationView
andNavigationLink
:Result
Additional information
To add a “close” button to a modal view we can use a
dismiss
closure provided by theModalLink
:Moving the destination in the code above to a separate structure is a recommended way here to refactor the code here as modal views regularly contains a bit more that just a text or button.
Learn more here: Display Modal View with SwiftUI