How to update a view depending on button click from other view in SwiftUI

Viewed 1097

I often face this situation but so far I could not find a good solution. Thing is when my SwiftUI View gets bigger I refactor the code by making another struct and call the struct in the respective view. Say I got a struct A and I refactor some code in struct B, but how can I update the view or call a function in struct A depending on button click on struct B ? The below code might help to understand the situation:

import SwiftUI

struct ContentView: View {
  @State var myText: String = "Hello World"
  @State var isActive: Bool = false
  var body: some View {
      VStack {
          Text(self.myText)
          AnotherStruct(isActive: $isActive)
      }
      .onAppear {
          if self.isActive == true {
              self.getApi()
          }
      }
  }

  func getApi() {
      print("getApi called")
      self.myText = "Hello Universe"
    }
  }

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
      ContentView()
  }
}

struct AnotherStruct: View {
  @Binding var isActive: Bool
  var body: some View {
      VStack {
          Button( action: {
              self.isActive.toggle()
          }) {
              Text("Button Tapped")
          }
      }
  }
}
1 Answers

Here is a demo of possible approach to solve such cases - with separated responsibility and delegated activity.

struct ContentView: View {
    @State var myText: String = "Hello World"

    var body: some View {
        VStack {
            Text(self.myText)
            AnotherStruct(onActivate: getApi)
        }
    }

    func getApi() {
        print("getApi called")
        self.myText = "Hello Universe"
    }
}

struct AnotherStruct: View {
    let onActivate: () -> ()

//  @AppStorage("isActive") var isActive      // << possible store in defaults

    var body: some View {
        VStack {
            Button( action: {
        //      self.isActive = true
                self.onActivate()
            }) {
                Text("Button Tapped")
            }
        }
//      .onAppear {
//        if isActive {
//            self.onActivate()
//        }
//      }
    }
}
Related