SwiftUI Modal Tutorial

To present modals, SwiftUI provides the special view modifier called sheet.In this tutorial a modal is presented which will include as dismiss button. SwiftUI requires Xcode 11 and MacOS Catalina, which can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIModalTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

The modal will be created form its own view. Add a new file to the project. Choose File -> New -> File and choose iOS -> User Interface -> SwiftUI View. The file will be named ModalView.swift.

Change the code inside the ModalView.swift to

struct ModalView: View {
    // 1.
    @Binding var showModal: Bool
    
    var body: some View {
        VStack {
            Text("Inside Modal View")
                .padding()
            // 2.
            Button("Dismiss") {
                self.showModal.toggle()
            }
        }
    }
}

struct ModalView_Previews: PreviewProvider {
    static var previews: some View {
        ModalView(showModal: .constant(true))
    }
}
  1. A Binding property is declared which will be used to dismiss the modal when false

  2. When the button is tapped, the modal will be dismissed

In the Project navigator, click to select ContentView.swift. In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

Change the code inside the ContentView struct to

struct ContentView: View {
    
    // 1.
    @State private var showModal = false
    
    var body: some View {
      
       Button("Show Modal") {
          // 2.
          self.showModal.toggle()
       // 3.
       }.sheet(isPresented: $showModal) {
            ModalView(showModal: self.$showModal)
        }
    }
}
  1. A state property is created which will present the modal when true

  2. The modal is presented when the show modal button is tapped. The showModal argument will be passed to the ModalView

Go to the preview window en click the live view button, Press the “show modal” button to present the modal. A swipe down will dismiss the modal, but the “Dismiss” button can also be used.

The source code of the SwiftUIModalTutorial can be downloaded at the ioscreator repository on Github.