I want to change the state of a subview via a function call of the subview. But the view is not updating.
struct MainView: View {
var subView: SubView = SubView()
var body: some View {
subView
Button("Button") {
subView.change()
}
}
}
struct SubView: View {
@State private var enabled = false
var body: some View {
if enabled {
Text("Some Label")
}
}
public func change() {
enabled.toggle()
}
}
It is possible to to this with @Binding, like it ist described here: https://www.hackingwithswift.com/forums/swiftui/calling-functions-of-sub-views/1960
But I am not happy with this solution, because I want to extract a view completely. With @Binding I still got some subview stuff in my mainview.
If it is
Stateto the view, you always want to keep it in that view, and not affect it from another view. The solution is to put the button in the subview and directly access the@State var enabledthere. Also, the way you wrote this would have given you multiple views. You always want a view struct to return a single view, so I stuck theTextandButtoninto aVStack