Home > Blockchain >  SwiftUI: Change param using call back
SwiftUI: Change param using call back

Time:12-09

I am looking at how I can change a param using a call back.

struct MainView: View {
  
  @State var name = "Original Name"
  
  var body: some View {
    VStack(spacing: 16) {
      FirstView(doChangeName: self.changeName)
      Text(name)
    }
    .padding(32)
  }
  
  func changeName() {
    print("Changing Name")
    self.name = "Another Name"
  }
  
}

struct FirstView : View {
  var doChangeName : () -> ()
  var body: some View {
    Button(action: {
      let newName = "New Name"
      self.doChangeName()
      
    }) { Text("Change Name") }
  }
}

When I click on change name button, it will be change to "Another Name". How can it be a param derived from a child view and in this case variable newName done through call back.

In another words, pass the newName variable back to function changeName.

CodePudding user response:

You can do it easily with binding but as you mention you want to use a closure with param.

Change closure syntax.

struct MainView: View {
    
    @State var name = "Original Name"
    
    var body: some View {
        VStack(spacing: 16) {
            FirstView(doChangeName: self.changeName)
            Text(name)
        }
        .padding(32)
    }
    
    func changeName(_ name: String) { // <== Here
        print("Changing Name")
        self.name = name
    }
    
}

struct FirstView : View {
    var doChangeName : (String) -> () // <== Here
    var body: some View {
        Button(action: {
            self.doChangeName("New Name")
            
        }) { Text("Change Name") }
    }
}
  • Related