Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: Change param using call back

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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") }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading