HomeiOS Developmentios - Unsuitable worth despatched to second view the primary time it's...

ios – Unsuitable worth despatched to second view the primary time it’s handed from the mum or dad view


Within the following code, I am making an attempt to move a bool to SecondView when a button is tapped. I am altering the state of the bool inside a Segmented/PickerView, what’s tricking me is the truth that if I run the app, faucet on the Turned Off section which updates the isRunning bool to false, after which faucet on the Present Second View button, I get true in Second View, and I used to be anticipating false because it was modified throughout the segmented/picker view earlier than sending it.

The humorous factor is that every part begins working as anticipated if I faucet on the Turned Off section, go to Second View, come again, faucet on the Began then faucet on the Turned Off section once more, and present the Second View once more, then I begin getting the correct values.

Any concept why the primary time I am going to Second View after tapping on the Turned Off section I get the unsuitable worth for isRunninginSecond View`?

Most important View

struct ContentView: View {
    @State non-public var onOffSegments = 1
    @State non-public var isRunning = true
        
    @State non-public var secondViewIsPresented = false
    
    var physique: some View {
        VStack {
            Picker("", choice: $onOffSegments) {
                Textual content("Began")
                    .tag(1)
                Textual content( "Turned Off")
                    .tag(2)
            }
            .pickerStyle(.segmented)
            .onChange(of: onOffSegments, carry out: { worth in
                if worth == 1{
                    isRunning = true
                    print("Is Operating:(isRunning)")
                }else{
                    isRunning = false
                    print("Is Operating: (isRunning)")
                }
            })
            
            Button("Present Second View"){
                secondViewIsPresented = true
            }
        }
        .padding()
        .sheet(isPresented: $secondViewIsPresented){
            SecondView(isRunning: isRunning)
        }
    }
}

Second View

struct SecondView: View {
    var isRunning: Bool
    
    var physique: some View {
        Textual content("Second View")
            .onAppear{
                print("OnAppear SecondView, Is Operating: (isRunning)")
            }
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments