Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State variable value is being lost

Tags:

swiftui

Im have the following code running in ios 1. When the button "View A" is pressed the state variable nextModalView2 is set to NextModalView2.a But When the Sheet() call is executed the value of nextModalView2 is reset to .none.

How is it possible?

Alsoif you look at the screenshot, you will see that the debugger console panel is showing a value for nextModalView2 that is different from what shown in the variable panel of the debugger. How is that?

enter image description here


enum NextModalView2{
  case none
  case a
  case b
}

struct Menu2: View {
  @State private var isShowModally = false
  @State private var nextModalView2 = NextModalView2.none

  var body: some View {
    VStack(alignment: .center) {
      Button(action: {
        self.isShowModally = true
        self.nextModalView2 = .a
        print("self.nextModalView = \(self.nextModalView2)")
      }){ Text("View A")
      }
      Divider()
      Button(action: {
        self.isShowModally = true
        self.nextModalView2 = .b
      }){ Text("View B")
      }
      .padding(.top, 20)
    }
    .sheet(isPresented:  $isShowModally){
      Group{
        if self.nextModalView2 == .a {
          //        case NextModalView2.a:
          AnyView(Text("A"))
        }
        if  self.nextModalView2 == NextModalView2.b{
          AnyView(Text("B"))
        }
        if self.nextModalView2 == NextModalView2.none{
          AnyView(EmptyView())
        }
      }
    }
  }
}
like image 603
onthemoon Avatar asked Mar 05 '26 15:03

onthemoon


1 Answers

We need to use sheet(item: modifier in such scenario, it works per-selection.

Here is a solution. Tested with Xcode 12.1 / iOS 14.1.

demo

enum NextModalView2: Identifiable{
    var id: NextModalView2 { self }
    case none
    case a
    case b
}

struct Menu2: View {
    @State private var nextModalView2: NextModalView2?
    
    var body: some View {
        VStack(alignment: .center) {
            Button(action: {
                self.nextModalView2 = .a
                print("self.nextModalView = \(self.nextModalView2 ?? .none)")
            }){ Text("View A")
            }
            Divider()
            Button(action: {
                self.nextModalView2 = .b
            }){ Text("View B")
            }
            .padding(.top, 20)
        }
        .sheet(item: $nextModalView2){ item in
            switch item {
            case .a:
                Text("A")
            case .b:
                Text("B")
            default:
                EmptyView()
            }
        }
    }
}
like image 54
Asperi Avatar answered Mar 07 '26 05:03

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!