Search code examples
swiftuiswiftui-listswiftui-navigationviewswiftui-tabviewswiftui-button

Using sheet for presenting different views on 2 buttons actions are presenting view incorrect view


enum ActiveSheet: Identifiable {
    case first, second
    
    var id: Int {
        return hashValue
    }
}
struct ContentView: View {
    @State var activeSheet: ActiveSheet?
    var body: some View {
        NavigationView {
            List(0..<20) { item in
                HStack {
                    Text("Item Row: \(item)")
                    Spacer()
                    Button("#1") {
                        self.activeSheet = .first
                    }
                    Spacer()
                    Button("#2") {
                        self.activeSheet = .second
                    }
                }
                .sheet(item: $activeSheet) { item in
                    switch item {
                    case .first:
                        View1()
                    case .second:
                        View2()
                    }
                }
            }
        }
    }
}
struct View1: View {
    var body: some View {
        Text("View1")
            .foregroundColor(.secondary)
    }
}

struct View2: View {
    var body: some View {
        Text("View2")
            .foregroundColor(.secondary)
    }
}

I have tried the above one but it's not working as expected for different button's action sheet. Here it opens up View2 view only irrespective of button action ( either #1 or #2). Home page Modal screen


Solution

  • You're actually tapping on List row. If you put debug points inside button actions, you can easily see that it will jump to #1 then #2 after, that's why it's always showing up View2. Try to make buttons's size bigger and change buttonStyle to plain.

    ...
    HStack {
        Text("Item Row: \(item)")
    
        Spacer()
    
        Button("#1") {
            self.activeSheet = .first
        }
        .buttonStyle(.plain)
    
        Spacer()
    
        Button("#2") {
            self.activeSheet = .second
        }
        .buttonStyle(.plain)
    }
    ...