SwiftUI – How to show a sheet view modally

By | 28/08/2020

In this post, we will see how to show a sheet view modally in Swift, after pressing a Button.

We start creating a SwiftUI view called Page2, that it will be the sheet view:

[PAGE2.SWIFT]

import SwiftUI

struct Page2: View {
    // definition of a Environment variable, used to dismiss the view
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        VStack{
            Text("Second View")
            
            // Pressing the button, the view will be dismissed
            Button(action: {self.presentationMode.wrappedValue.dismiss()
            })
            {
                Text("Dismiss")
            }
        }
    }
}

struct Page2_Previews: PreviewProvider {
    static var previews: some View {
        Page2()
    }
}



Then, we define the started page called ContentView, where we will add a button used to show the Page2 view:

import SwiftUI

struct ContentView: View {
    // Definition of the variable showingUtility,
    // used to show the Page2 view
    @State var showingUtility = false
    var body: some View {
        VStack{
            Text("Start Page")
                .font(.largeTitle)
            
            Button(action: {
                self.showingUtility.toggle()
            })
            {
                Text("Go to the second page")
            }
            .sheet(isPresented: $showingUtility)
            {
                Page2()
            }
        }
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}





Leave a Reply

Your email address will not be published.