Home > front end >  How to update UI of a view from another view [ SwiftUI Question]
How to update UI of a view from another view [ SwiftUI Question]

Time:01-27

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!

CodePudding user response:

You can achieve this by passing the textValue from MainView to DetailView through a @Binding.

struct MainView: View {
    @State private var text: String = "Original"

    var body: some View {
        NavigationView {
            VStack {
                Text(text)
                NavigationLink("Detail", destination: DetailView(text: $text))
            }
        }
    }
}

struct DetailView: View {
    @Binding var text: String
    
    var body: some View {
        Button("Change Text") {
            text = "New Text"
        }
    }
}

I recommend you read this article about bindings as it explains how to change a view from elsewhere.

Edit: Because you mentioned, that both views are in a TabBar, here should be a working example:

struct ContentView: View {
    @State private var text: String = "Original Text"
    
    var body: some View {
        TabView {
            MainView(text: $text)
                .tabItem { ... }
            DetailView(text: $text)
                .tabItem { ... }
        }
    }
}

struct MainView: View {
    @Binding var text: String

    var body: some View {
        Text(text)
    }
}

struct DetailView: View {
    @Binding var text: String

    var body: some View {
        Button("Change Text") {
            text = "New Text"
        }
    }
}
  •  Tags:  
  • Related