How do I add closures to Viewmodifiers in SwiftUI?

Viewed 901

I am using the ClearButton ViewModifier here

.modifier(ClearButton(text: $someBinding))

But I want to run a function after clear textfield. Like this or similar

.modifier(ClearButton(text: $someBinding)) {
      print("")
}

Is it possible?

1 Answers

You can pass a function as a parameter like this:

struct ClearButton: ViewModifier {
    @Binding var text: String
    var action: () -> Void = {} // pass the function here

    public func body(content: Content) -> some View {
        ZStack(alignment: .trailing) {
            content

            if !text.isEmpty {
                Button(action: {
                    self.text = ""
                    action() // call the `action` here
                }) {
                    Image(systemName: "delete.left")
                        .foregroundColor(Color(UIColor.opaqueSeparator))
                }
                .padding(.trailing, 8)
            }
        }
    }
}

and apply this modifier to your TextField:

struct ContentView: View {
    @State private var text = ""

    var body: some View {
        TextField("Some Text", text: $text)
            .modifier(
                ClearButton(text: $text) {
                    print("TextField cleared")
                }
            )
    }
}

Note that if you want to skip the label for the trailing closure, the action parameter must come last.

Related