[ad_1]
On this instance, the blue rectangle must be initially seen on gadgets with .common measurement class and hidden on gadgets with .compact measurement class.
I am utilizing an ObservableObject referred to as Settings and the @Printed variable isVisible to handle visibilty of the rectangle. My downside is that I do not understand how I can init Settings with the proper horizontalSizeClass from my ContentView. Proper now I’m utilizing .onAppear to alter the worth of isVisible however this triggers .onReceive. On compact gadgets this causes the rectangle to be seen and fading out when the view is introduced as a substitute of being invisible immediately.
How can I init Settings based mostly on Setting values like horizontalSizeClass in order that isVisible is right from the beginning?
struct ContentView: View {
@Setting(.horizontalSizeClass) var horizontalSizeClass
@StateObject var settings = Settings()
@State var opacity: CGFloat = 1
var physique: some View {
VStack {
Button("Toggle Visibility") {
settings.isVisible.toggle()
}
.onReceive(settings.$isVisible) { _ in
withAnimation(.linear(period: 2.0)) {
opacity = settings.isVisible ? 1 : 0
}
}
Rectangle()
.body(width: 100, top: 100)
.foregroundColor(.blue)
.opacity(opacity)
}
.onAppear {
settings.isVisible = horizontalSizeClass == .common // too late
}
}
}
class Settings: ObservableObject {
@Printed var isVisible: Bool = true // cannot get measurement class right here
}
The rectangle shouldn’t be seen on begin:
[ad_2]

