iosswiftswiftui

SwiftUI sheet doesn't access the latest value of state variables on first appearance


It seems like the state variable are not properly updated when a sheet is displayed for the first time.

For instance with this code:

import SwiftUI

struct DemoView: View {
    @State var showDetails: Bool = false
    var body: some View {
        VStack {
            Button(action: {
              showDetails = true
            }) {
                Text("Show sheet")
            }
        }.sheet(isPresented: $showDetails){
            VStack {
                Text("showDetails: \(showDetails ? "yes" : "no")")
            }
        }
    }
}

struct DemoView_Previews: PreviewProvider {
    static var previews: some View {
        DemoView()
    }
}

This will display "no" on first click, and "yes" on second, as showcased here:

enter image description here

Am I missing something? How can I make sure my state variables are properly read by the sheet view?


Solution

  • You see value on time of sheet creation. If you want to track parent view state create sheet subview with binding to that state, like below. Binding will update subview when subview will appear.

    Tested with Xcode 12 / iOS 14
    Re-tested with Xcode 13.3 / iOS 15.4

    struct DemoView: View {
        @State var showDetails: Bool = false
        var body: some View {
            VStack {
                Button(action: {
                  showDetails = true
                }) {
                    Text("Show sheet")
                }
            }.sheet(isPresented: $showDetails){
                SheetDetailView(flag: $showDetails)
            }
        }
    }
    
    struct SheetDetailView: View {
        @Binding var flag: Bool
        var body: some View {
            VStack {
                Text("showDetails: \(flag ? "yes" : "no")")
            }
        }
    }