SwiftUI: How to change subview?

702 views Asked by At

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.

1

There are 1 answers

0
Yrb On

If it is State to 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 enabled there. 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 the Text and Button into a VStack

struct MainView: View {

    var body: some View {
        SubView()
    }
}

struct SubView: View {

    @State private var enabled = false

    var body: some View {
        VStack {
            if enabled {
                Text("Some Label")
            }
            Button("Button") {
                enabled.toggle()
            }
        }
    }
}