📜  fullscreencover swiftui - Swift (1)

📅  最后修改于: 2023-12-03 14:41:20.835000             🧑  作者: Mango

FullScreenCover SwiftUI - Swift

Introductions

The FullScreenCover view modifier in SwiftUI is used to present modal view in full screen mode. This is similar to the sheet modifier but with full screen presentation. The FullScreenCover is a non-dismissable view, it must be dismissed manually.

Prerequisites
  • xCode 11 or later.
  • Swift 5 or later.
  • Basic knowledge of SwiftUI.
Implementation

Here's an example code snippet of using FullScreenCover to present a modal view in full screen mode.

struct ContentView: View {
    @State private var isModalPresented = false
    
    var body: some View {
        Button(action: {
            self.isModalPresented.toggle()
        }) {
            Text("Present Full Screen Modal").padding()
        }
        .fullScreenCover(isPresented: $isModalPresented, content: {
            ModalView(isModalPresented: self.$isModalPresented)
        })
    }
}

struct ModalView: View {
    @Binding var isModalPresented: Bool
    
    var body: some View {
        VStack {
            Text("Full Screen Modal View")
                .font(.title)
            
            Button(action: {
                self.isModalPresented.toggle()
            }) {
                Text("Dismiss Modal").padding()
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
    }
}

In the above code, we first declare a boolean state variable isModalPresented to keep track of the modal presentation status. We then create a button with an action to toggle the isModalPresented variable when tapped.

Next, we use the .fullScreenCover modifier on the button to present the ModalView in full screen mode. The ModalView must accept a binding to isModalPresented to allow the view to dismiss itself when the "Dismiss Modal" button is tapped.

Inside the ModalView, we define our view hierarchy with a VStack containing a title and a button to dismiss the modal view.

Conclusion

The FullScreenCover view modifier is a useful tool for presenting modal views in full screen mode in SwiftUI. With a little bit of setup and the .fullScreenCover modifier, it's easy to present and dismiss full screen modal views in SwiftUI.