I'm trying to setup a view that can display multiple modals depending on which button is tapped.
When I add just one sheet
, everything works:
.sheet(isPresented: $showingModal1) { ... }
But when I add another sheet, only the last one works.
.sheet(isPresented: $showingModal1) { ... } .sheet(isPresented: $showingModal2) { ... }
UPDATE
I tried to get this working, but I'm not sure how to declare the type for modal
. I'm getting an error of Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
.
struct ContentView: View { @State var modal: View? var body: some View { VStack { Button(action: { self.modal = ModalContentView1() }) { Text("Show Modal 1") } Button(action: { self.modal = ModalContentView2() }) { Text("Show Modal 2") } }.sheet(item: self.$modal, content: { modal in return modal }) } } struct ModalContentView1: View { var body: some View { Text("Modal 1") } } struct ModalContentView2: View { var body: some View { Text("Modal 2") } }
Modal views are views that are presented over the main application and prevent interaction with the views behind until the modal view is dismissed. There are different types of modal views available in SwiftUI, each designed for a particular function.
This approach is much safer, because we use the enumeration type to keep everything well organized. Let's see it in action. Modal views in SwiftUI are presented using the sheet modifier on a view or control. The simplest way is to have @State property to indicate when it should be visible.
We can attach sheet function to any SwiftUI view or control, for instance to the Button: It can be fine to have two buttons, but let's say we have more than that. It can get quite messy, so we should deal with many @State variables. If we look at Apple's official documentation, there is another function) to show a sheet. Let's try to use it.
The simplest way is to have @State property to indicate when it should be visible. To hide the modal view, we can use the environment parameter or pass a binding to the modal view object. Showing multiple sheets can be achieved either with multiple sheet modifiers or using an object with all possible modal view enumerations.
This works:
.background(EmptyView().sheet(isPresented: $showingModal1) { ... } .background(EmptyView().sheet(isPresented: $showingModal2) { ... }))
Notice how these are nested backgrounds
. Not two backgrounds one after the other.
Thanks to DevAndArtist for finding this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With