Multiple sheet(isPresented:) doesn't work in SwiftUI
Best way to do it, which also works for iOS 14:
enum ActiveSheet: Identifiable {
case first, second
var id: Int {
hashValue
}
}
struct YourView: View {
@State var activeSheet: ActiveSheet?
var body: some View {
VStack {
Button(action: {
activeSheet = .first
}) {
Text("Activate first sheet")
}
Button(action: {
activeSheet = .second
}) {
Text("Activate second sheet")
}
}
.sheet(item: $activeSheet) { item in
switch item {
case .first:
FirstView()
case .second:
SecondView()
}
}
}
}
Read more here: https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:)
To hide the sheet just set activeSheet = nil
Bonus:
If you want your sheet to be fullscreen, then use the very same code, but instead of .sheet
write .fullScreenCover
Please try below code
Update Answer (iOS 14, Xcode 12)
enum ActiveSheet {
case first, second
var id: Int {
hashValue
}
}
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!")
}
}
}
}
}
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)
}
}