Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI sheet never updated after first launch

Tags:

swiftui

I use a modal sheet whose content is updated for each call. However, when the content is marked as @State, the view body is never updated.

Is anyone seeing this as well? Is a workaround available?

This is the calling view:

struct ContentView: View {
    @State var isPresented = false
    @State var i = 0

    var body: some View {
        List {
            Button("0") {
                self.i = 0
                self.isPresented = true
            }
            Button("1") {
                self.i = 1
                self.isPresented = true
            }
        }
        .sheet(
            isPresented: $isPresented,
            content: {
                SheetViewNOK(i: self.i)
            }
        )
    }
}

This does work:

struct SheetViewOK: View {
    var i: Int

    var body: some View {
        Text("Hello \(i)") // String is always updated
    }
}

This does not work. But obviously, in a real app, I need to use @State because changes made by the user need to be reflected in the sheet's content:

struct SheetViewNOK: View {
    @State var i: Int

    var body: some View {
        Text("Hello \(i)") // String is never updated after creation
    }
}
like image 511
caram Avatar asked Feb 02 '26 09:02

caram


1 Answers

In your .sheet you are passing the value of your ContentView @State to a new @State. So it will be independent from the ContentView.

To create a connection or a binding of your ContentView @State value, you should define your SheetView var as @Binding. With this edit you will pass the binding of your state value to your sheet view.

struct SheetView: View {
    @Binding var i: Int

    var body: some View {
        Text("Hello \(i)")
    }
}

struct ContentView: View {
    @State var isPresented = false
    @State var i: Int = 0

    var body: some View {

        List {
            Button("0") {
                self.i = 0
                self.isPresented = true
            }
            Button("1") {
                self.i = 1
                self.isPresented = true
            }
        }.sheet(
            isPresented: $isPresented,
            content: {
                SheetView(i: self.$i)
        })
    }
}
like image 165
Giuseppe Sapienza Avatar answered Feb 05 '26 09:02

Giuseppe Sapienza



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!