In this example, the blue rectangle should be initially visible on devices with .regular size class and hidden on devices with .compact size class.
I'm using an ObservableObject called Settings and the @Published variable isVisible to manage visibilty of the rectangle. My problem is that I don't know how I can init Settings with the correct horizontalSizeClass from my ContentView. Right now I am using .onAppear to change the value of isVisible but this triggers .onReceive. On compact devices this causes the rectangle to be visible and fading out when the view is presented instead of being invisible right away.
How can I init Settings based on Environment values like horizontalSizeClass so that isVisible is correct from the start?
struct ContentView: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@StateObject var settings = Settings()
@State var opacity: CGFloat = 1
var body: some View {
VStack {
Button("Toggle Visibility") {
settings.isVisible.toggle()
}
.onReceive(settings.$isVisible) { _ in
withAnimation(.linear(duration: 2.0)) {
opacity = settings.isVisible ? 1 : 0
}
}
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.blue)
.opacity(opacity)
}
.onAppear {
settings.isVisible = horizontalSizeClass == .regular // too late
}
}
}
class Settings: ObservableObject {
@Published var isVisible: Bool = true // can't get size class here
}
The rectangle should not be visible on start:

