Hi everybody, after updating to 14 iOS ran into a problem. When calling Sheet, there is a later update of the variable from the second time. I will give an example:
The first time the button is clicked, the testVar variable changes, but inside sheet it is not changed. When you press the button again, everything works as expected. On iOS 13 everything works without errors. Maybe I'm doing something wrong or I missed the information that something has changed. If anyone comes across, help or tell me where to look. Very grateful in advance for any answer.
Code Block @State var showTestSheet : Bool = false @State var testVar : Bool = false Button(action: { self.testVar.toggle() self.showTestSheet = true }) { Text("Test") } .sheet(isPresented: self.$showTestSheet, content: { if(self.testVar) { Text("True") } else { Text("False") }})
The first time the button is clicked, the testVar variable changes, but inside sheet it is not changed. When you press the button again, everything works as expected. On iOS 13 everything works without errors. Maybe I'm doing something wrong or I missed the information that something has changed. If anyone comes across, help or tell me where to look. Very grateful in advance for any answer.
There are several reports which say @State variables do not work as expected in sheet.
This is one of them.
Issue with .sheet() Passing String to a View in SwiftUI 2.0
In my opinion, this is a bug of the current implementation of SwiftUI. You should better send a feedback to Apple.
But, iOS 14 is released with this bug unfixed, so we need some workaround.
One way is:
There may be another better way, but this one works as expected as far as I tested.
This is one of them.
Issue with .sheet() Passing String to a View in SwiftUI 2.0
In my opinion, this is a bug of the current implementation of SwiftUI. You should better send a feedback to Apple.
But, iOS 14 is released with this bug unfixed, so we need some workaround.
One way is:
Pass a Binding instead of the value of the @State variable
Use the value of the Binding in the body of the view included in the sheet
Code Block import SwiftUI struct ContentView: View { @State var showTestSheet : Bool = false @State var testVar : Bool = false var body: some View { Button(action: { self.testVar.toggle() self.showTestSheet = true }) { Text("Test") } .sheet(isPresented: self.$showTestSheet) { TestSheetView(testVar: self.$testVar) } } } struct TestSheetView: View { @Binding var testVar: Bool var body: some View { if self.testVar { Text("True") } else { Text("False") } } }
There may be another better way, but this one works as expected as far as I tested.