top of page
Writer's pictureHui Wang

13. SwiftUI: Open a modal window via Button


Today I will introduce how to use the sheet method of the Button control to open a modal window with specified content.


Knowledge points:

  • First, add a property to the current struct.

  • This property is a Bool type. It is used to determine whether to show or hide the modal window.

@State var isPresented = false

  • Next, add a Button control and set its title.

  • When the button is clicked, set the Bool property to true.

  • Call the sheet method of the Button control and set the value of isPresented to the current Bool property.

  • When the value of the property is true, the content in the sheet is displayed.

struct ContentView: View {
    
    @State var isPresented = false
    
    var body: some View {
        VStack {
            Button("Show modal") {
                isPresented = true
            }.sheet(isPresented: $isPresented) {
                //
            } content: {
                //
            }
        }
    }
}

  • Define a struct that conforms to the View protocol as a new custom view.

  • struct is more lightweight than class, so SwiftUI uses struct to define visual controls.

  • Add a String type property to the custom view.

  • Implement the body property that must be implemented in the View protocol, and all elements in the custom view should be placed in the body.

  • Add a VStack view as a container for subviews.

  • Add a Text view to display the value of the property and set the font style to largeTitle.

struct MyView: View {
    let message: String
    var body: some View {
        VStack {
            Text(message)
                .font(.largeTitle)
        }
    }
}

  • Then use this custom view as the sheet content of the Button control.

content: {
    MyView(message: "Model window")
}

  • Click the Live Preview button to enter Live Preview mode.

  • Click the button to open a custom modal window.

  • Drag down from the top of the window to close the window.


Visual effects:


After code:

struct ContentView: View {
    
    @State var isPresented = false
    
    var body: some View {
        VStack {
            Button("Show modal") {
                isPresented = true
            }.sheet(isPresented: $isPresented) {
                //
            } content: {
                MyView(message: "Model window")
            }
        }
    }
}

struct MyView: View {
    let message: String
    var body: some View {
        VStack {
            Text(message)
                .font(.largeTitle)
        }
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

 

Follow me on:

Comments


bottom of page