问题
I have this ContentView with two different modal views, so I'm using sheet(isPresented:)
for both, but as it seems only the last one gets presented. How could I solve this issue? Or is it not possible you use multiple sheets on a view in SwiftUI?
struct ContentView: View {
@State private var firstIsPresented = false
@State private var secondIsPresented = false
var body: some View {
NavigationView {
VStack(spacing: 20) {
Button("First modal view") {
self.firstIsPresented.toggle()
}
Button ("Second modal view") {
self.secondIsPresented.toggle()
}
}
.navigationBarTitle(Text("Multiple modal view problem"), displayMode: .inline)
.sheet(isPresented: $firstIsPresented) {
Text("First modal view")
}
.sheet(isPresented: $secondIsPresented) {
Text("Only the second modal view works!")
}
}
}
}
The above code compiles without warnings (Xcode 11.2.1).
回答1:
Please try below code
enum ActiveSheet {
case first, second
}
struct ContentView: View {
@State private var showSheet = false
@State private var activeSheet: ActiveSheet = .first
var body: some View {
NavigationView {
VStack(spacing: 20) {
Button("First modal view") {
self.showSheet = true
self.activeSheet = .first
}
Button ("Second modal view") {
self.showSheet = true
self.activeSheet = .second
}
}
.navigationBarTitle(Text("Multiple modal view problem"), displayMode: .inline)
.sheet(isPresented: $showSheet) {
if self.activeSheet == .first {
Text("First modal view")
}
else {
Text("Only the second modal view works!")
}
}
}
}
}
回答2:
Can also add the sheet to an EmptyView placed in the view's background. This can be done multiple times:
.background(EmptyView()
.sheet(isPresented: isPresented, content: content))
回答3:
You're case can be solved by the following (tested with Xcode 11.2)
var body: some View {
NavigationView {
VStack(spacing: 20) {
Button("First modal view") {
self.firstIsPresented.toggle()
}
.sheet(isPresented: $firstIsPresented) {
Text("First modal view")
}
Button ("Second modal view") {
self.secondIsPresented.toggle()
}
.sheet(isPresented: $secondIsPresented) {
Text("Only the second modal view works!")
}
}
.navigationBarTitle(Text("Multiple modal view problem"), displayMode: .inline)
}
}
来源:https://stackoverflow.com/questions/58837007/multiple-sheetispresented-doesnt-work-in-swiftui