'How to update UI of a view from another view [ SwiftUI Question]

I am new to Swift & iOS dev in general.

I am building an app in SwiftUI. Assume there are 2 separate views in different files: MainView() & Results() and TabBar()(ignore the naming, this is just an example)(those 2 views are ON 2 SEPARATE TABS)

My goal is to press on that button FROM ResultsView() and change the textValue property of MainView() to something else & then display the change ON the MainView(). How can I do that? P.S Please ignore alignment & etc. I am new to StackOverflow

struct MainView: View {
    
    @State var textValue: String = "Old Text"
    
    var body: some View {
        Text(textValue)
    }
    
}

struct TabBar: View {
    var body: some View {
        TabView {
            MainView()
                .tabItem {
                    Label("Main", systemImage: "circle.dashed.inset.filled")
                }
            ResultsView()
                .tabItem {
                    Label("Results", systemImage: "person.2.crop.square.stack.fill")
                }
        }
    }
}

struct ResultsView: View {
    
    var body: some View {
        Button {
            // HOW TO UPDATE MainView.textValue?
        } label: {
            Text("Update")
        }
    }
}
  • ContentView() just has TabBar() in body

Basically, my question is how do we change UI of certain view from another view? Without NavigationLink

Might sound like a rookie question, but any reply will be so appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source