SwiftUI: Switch .sheet on enum, does not work

With some very small alterations to your code, you can use sheet(item:) for this, which prevents this problem:


//MARK: main view:
struct ContentView: View {
    
    //construct enum to decide which sheet to present:
    enum ActiveSheet : String, Identifiable { // <--- note that it's now Identifiable
        case sheetA, sheetB
        var id: String {
            return self.rawValue
        }
    }
    
    @State var activeSheet : ActiveSheet? = nil // <--- now an optional property
    
    var body: some View {
        
        
        VStack{
            
            Button(action: {
                self.activeSheet = .sheetA
            }) {
                Text("Show Sheet A")
            }
            
            
            Button(action: {
                self.activeSheet = .sheetB 
            }) {
                Text("Show Sheet B")
            }
        }
        //sheet choosing view to display based on selected enum value:
        .sheet(item: $activeSheet) { sheet in // <--- sheet is of type ActiveSheet and lets you present the appropriate sheet based on which is active
            switch sheet {
            case .sheetA:
                SheetA() 
            case .sheetB:
                SheetB()
            }
        }
    }
}

The problem is that without using item:, current versions of SwiftUI render the initial sheet with the first state value (ie sheet A in this case) and don’t update properly on the first presentation. Using this item: approach solves the issue.

Leave a Comment