As far as I know, @State (or @Binding) only works within a View.
If used outside of a view, state changes will not be applied to the View or an error will be encountered stating that it has not been installed on a View.
However, in ViewModifiers or ButtonStyles, @State works well, like in the following example
struct MyViewModifier: ViewModifier {
@State
var isHidden: Bool = true
func body(content: Content) -> some View {
VStack {
Button("Toggle Hidden State") { isHidden.toggle() }
if !isHidden {
content
}
}
}
}
How dose it works?
I'm guessing it adopts DynamicProperty, Then it makes sense. However, I couldn't find any adaptation codes on the public interface.