21

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?

0

5 Answers 5

20

While there are answers here that show how to mitigate this issue, I feel none of them explains why the issue happens or why the fix works which is in my opinion more important then blindly using a fix.

Basically, it seems that SwiftUI will reevaluate the DemoView body if any @State property is accessed when it first evaluates it. Since showDetails property is set only in the Button action callback and accessed in the sheet content view builder callback which are not executed in the body SwiftUI doesn't appear to know that it needs to reevaluate the body when it's updated on tap.

You can check that by adding a simple print in the body var like so:

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

After tapping the button there will be no body reevaluation. This is why showDetails value captured in the sheet is the initial false value.

If you were to use showDetails variable in the DemoView body, either displaying it, or just adding a simple print, you will see that the body is reevaluated and value you see in the sheet is up to date.

struct DemoView: View {
    @State var showDetails: Bool = false
    var body: some View {
        print("Body evaluated \(showDetails)")
        return VStack {
            Button(action: {
              showDetails = true
            }) {
                Text("Show sheet")
            }
        }.sheet(isPresented: $showDetails){
            VStack {
                Text("showDetails: \(showDetails ? "yes" : "no")")
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'd like to add to this as I think it's the best answer. I had a simalar problem (didn't realise this was the same until this answer) and malhal answered it on mine (here: stackoverflow.com/a/76170215/769294) saying you can just add [showDetails] in at the start of the sheet closure e.g. .sheet(isPresented: $showDetails) { [showDetails] in and basically my understanding is it makes the view re-evaluate showDetails before passing it to the closure as it now knows it needs it! Feels much tidier if you don't need two way binding and just want the value passed in to the child view.
@GazB THIS is the real answer. This is another major gaffe in SwiftUI, but adding that capture syntax eliminates the problem. All I did was add the "[view state var] in" to the "content" closure, and the behavior changed from showing the old value to the current value.
16

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")")
        }
    }
}

Comments

14

You do not have to use the state variable in the body, you can just hint to the sheet that it is dependent on the state variable like so:

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){ [showDetails] in <-- add this
            VStack {
                Text("showDetails: \(showDetails ? "yes" : "no")")
            }
        }
    }
}

5 Comments

This actually works great for me, and is very simple. Is this a common pattern?
Yes, it works in many places where completions are in use. Maybe upvote this? I think it is more elegant than the above 'hack' of using it in the body.
This is the answer!
I actually find the new sheet(item:) API to work really well: developer.apple.com/documentation/swiftui/view/…
Unfortunately the suggested capture will result in a compile-time error if you try to set showDetails from inside the closure: "Cannot assign to value: 'showDetails' is an immutable capture".
2

Sometimes it's not possible to use @Binding. For example if we need to use a variable in the init block. My way:

struct DemoView: View {

    @State var showDetails = false
    @State var wtfGuys = false

    var body: some View {
        VStack {
            Button(action: {
                showDetails = true
            }) {
                Text("Show sheet")
            }
        }
                .sheet(isPresented: $showDetails) {
                    ZStack {
                        if wtfGuys {
                            VStack {
                                Text("showDetails: \(showDetails ? "yes" : "no")")
                            }
                        }
                    }
                            .onAppear { wtfGuys = true }
                            .onDisappear { wtfGuys = false }
                }
    }
}

Example with init block:

struct DemoView: View {

    @State var showDetails = false
    @State var wtfGuys = false

    var body: some View {
        VStack {
            Button(action: {
                showDetails = true
            }) {
                Text("Show sheet")
            }
        }
                .sheet(isPresented: $showDetails) {
                    ZStack {
                        if wtfGuys {
                            DetailView(showDetails: showDetails)
                        }
                    }
                            .onAppear { wtfGuys = true }
                            .onDisappear { wtfGuys = false }
                }
    }
}

struct DetailView: View {

    let showDetails: Bool

    init(showDetails: Bool) {
        print(showDetails) // true
        self.showDetails = showDetails
    }

    var body: some View {
        Text("showDetails: \(showDetails ? "yes" : "no")")
    }
}

One more case:

struct DemoView: View {

    @State var showDetails = false
    @State var detailsText = ""

    var body: some View {
        VStack {
            Button(action: {
                detailsText = "new text"
                showDetails = true
            }) {
                Text("Show sheet")
            }
        }
                // Here it is
                .onChange(of: showDetails) { _ in }
                .sheet(isPresented: $showDetails) {
                    Text("text: \(detailsText)")
                }
    }
}

4 Comments

This is what i am actually looking for because i do not want to create another struct and binding just for this. However, in the animation, i noticed it shows weirdly. Does your animation run smooth when showing the sheet?
@chitgoks For these examples the animation is smooth. I've experienced bad animation when I put onAppear/onDisappear inside "if wtfGuys".
I got it to work. Though I have a different problem now, if i display it as html, i get the AttributeGraph: cycle detected through attribute In Sheet. it's a different issue. thanks for this.
@chitgoks I added one more case to the answer.
0

I had the same problem with .fullScreenCover. Another way to trick SwiftUI into showing the right state is to add an EmptyView and set its disabled property to one of the state variables:

import SwiftUI

struct DemoView: View {
    @State var showDetails: Bool = false
    var body: some View {
        VStack {
            Button(action: {
              showDetails = true
            }) {
                Text("Show sheet")
            }

            // kludge: this ensures .sheet sees the latest state when first shown
            EmptyView().disabled(showDetails)
        }.sheet(isPresented: $showDetails){
            VStack {
                Text("showDetails: \(showDetails ? "yes" : "no")")
            }
        }
    }
}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.