mica
mica

Reputation: 4308

SwiftUI - call a func in a View from outside

is it possible to call a func of a View from outside.
I tried like this, but had no success.

@main
struct CallFromOutsideApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

struct ContentView: View {
  var body: some View {
    VStack{
      SubView()
      Button("Call alterX in ContentView"){
        // How to call alterX in SubView????
      }
    }
    .padding()
  }
}

struct SubView: View {
  @State var x = "Status A"
  
  var body: some View {
    VStack{
      Text("Status: \(x)")
      Button("Call alterX in SubView"){ alterX()
      }
    }
    .padding()
  }
  
  func alterX(){
    x = "Status B"
  }
}


Upvotes: 1

Views: 1082

Answers (1)

aheze
aheze

Reputation: 30228

EDIT

You shouldn't control SubView's @State from ContentView. Instead, put the @State in ContentView and pass it to a @Binding in SubView.

struct ContentView: View {
    @State var x = "Status A"
    var body: some View {
        VStack{
            
            SubView(x: $x) /// pass in the binding
            
            Button("Alter X in ContentView"){
                x = "Status B"
            }
        }
        .padding()
    }
}

struct SubView: View {
    @Binding var x: String
    
    var body: some View {
        VStack{
            Text("Status: \(x)")
            Button("Alter X in SubView") {
                x = "Status B"
            }
        }
        .padding()
    }
}

You could store SubView in a property. Like

struct ContentView: View {
  let subView = SubView()
  var body: some View {
    VStack{

      subView /// like this

      Button("Call alterX in ContentView"){
        subView.alterX() /// call it
      }
    }
    .padding()
  }
}

struct SubView: View {
  @State var x = "Status A"
  
  var body: some View {
    VStack{
      Text("Status: \(x)")
      Button("Call alterX in SubView"){ alterX()
      }
    }
    .padding()
  }
  
  func alterX(){
    x = "Status B"
  }
}

Upvotes: 3

Related Questions