Home > OS >  How to call method from another viewModel when sheet dismiss in SwiftUI?
How to call method from another viewModel when sheet dismiss in SwiftUI?

Time:11-03

I am having view and viewModel. I am navigating to sheet from view and doing few things and dismissing it, as soon as i dismiss sheet i want to call one method in viewModel.

In FirstView presenting sheet like

.sheet(isPresented: $showAddView) {
    AddView(viewModel: AddViewModel(showAddView: $showAddView))
 }

In FirstViewModel i want to call method on sheet dismiss

func update() {
   print("I get called")
   //some logic
}

in action sheet AddView

doing some logic and dismissing

Please help how should i call method. Thank you for help.

CodePudding user response:

If what you want is to know when the view was dismissed, you can observe changes to showAddView like this:

.sheet(isPresented: $showAddView) {
    AddView(viewModel: AddViewModel(showAddView: $showAddView))
}
.onChange(of: showAddView) { newValue 
    guard !newValue else { return }
    // Will be executed when newValue changes to false
    // I think it will also be called the first time your view is loaded
}

CodePudding user response:

A great solution for this is to pass a function as an argument. The general idea here is to match your function signature to get it to allow it. So on your FirstViewModel you've got your method update() you can pass that to the AddView() as a property of the object by doing something like this. Also this is particularly useful if you've got a value in your AddView that needs to be used in your update function.

First View Model

.sheet(isPresented: $showAddView) {
    AddView(viewModel: AddViewModel(showAddView: $showAddView), update: update)
}

AddView

Simply add a property to hold the passed function. Then call it on dismiss.

{
    let update: () -> ()
    // The rest of your view

    //Close Button
    Button(action {
        self.update()   
    }, label(...
}

What is a function signature?

Suppose your update function is this.

func update(someInt: Int) {
    //Do Something
}

You can match the signature by creating a property like this.

  • let someUpdateFunc: (Int) -> ()
  • The syntax is name: -> (Type) -> (Return Type)
  • It's also possible to have multiple types as an argument. For example
  • let someOtherFunc: (Int, String) -> ()

CodePudding user response:

.sheet(isPresented: $shouldAddView, onDismiss: viewModel.update) { ... }
  • Related