Here is a simple example. You can create new SwiftUI iOS project and copy it to ContentView file.
import SwiftUI
struct Settings {
static let onOff = "onOff"
}
struct ContentView: View {
@AppStorage(wrappedValue: false, Settings.onOff) var onOff
var body: some View {
NavigationView {
GeometryReader { reader in // < Comment out this line
List {
Section (header:
VStack {
HStack {
Spacer()
VStack {
Text("THIS SHOULD BE FULL-WIDTH")
Text("It is thanks to GeometryReader")
}
Spacer()
}
.padding()
.background(Color.yellow)
HStack {
Text("This should update from AppStorage: ")
Spacer()
Text(onOff == true ? "ON" : "OFF")
}
.padding()
}
.frame(width: reader.size.width) // < Comment out this line
.textCase(nil)
.font(.body)
) {
Toggle(isOn: $onOff) {
Text("ON / OFF")
}
}
}
.listStyle(GroupedListStyle())
} // < Comment out this line
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I have 3 elements:
- Text with yellow background - I need it full-width and I use GeometryReader to do it.
- Text. Last word should switch ON/OFF based on toggle value. This is just for testing purposes to check if AppStorage works correctly.
- Toggle - switches onOff variable and saves it to AppStorage (UserDefaults).
AppStorage works perfectly only without GeometryReader. Please comment out 3 tagged lines to check it out.
Is it a bug? Or something is wrong with my AppStorage code? Or maybe GeometryReader part is wrong? If I could set yellow part full-width, I could drop GeometryReader completely.