An analogue of SwiftUI NavigationView that provides a convenient interface of displaying modal views.
Add a dependency using Swift Package Manager to your project: https://github.com/diniska/modal-view
Import the dependency
import ModalViewUse ModalPresenter and ModalLink the same way you would use NavigationView and NavigationLink:
struct ContentView: View {
var body: some View {
ModalPresenter {
ModalLink(destination: Text("Modal View")) {
Text("Main view")
}
}
}
}There are two styles available: sheet (default) and fullScreenCover.
To change a style use method View.modalViewPresentationStyle.
An onModalViewPresent closure can be additionally provided to the ModalLink if some actions need to be done right before a modal view presents.
This can be useful for example for analytics or logging.
ModalLink(destination: Text("Modal View")) {
print("Presenting modal view")
} label: {
Text("Main view")
}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 as modal views regularly contain 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")
}
}
}Learn more here: Display Modal View with SwiftUI
