Tim
Tim

Reputation: 1928

SwiftUI how add custom modifier with callback

In SwiftUI you can wrote code like this:

List {
    ForEach(users, id: \.self) { user in
        Text(user)
    }
    .onDelete(perform: delete)
}

I try to add functionality with .onDelete syntax method to my custom component:

struct MyComponen: View {
    @Binding var alert: String

    .
    .
    .
}

I try to add this ability with extension:

extension MyComponent {

   func foo() -> Self { 
        var copy = self
        copy.alert = "Hohoho"
        return copy
    }

    func onDelete() -> Void { 

    }
}

How can I change state (or callback function with):

struct ContentView: View { 
    var body: some View {
        Group {
            MyComponent() //-> with alert = "state 1"
            MyComponent().foo() //-> with alert = "state 2"
            MyComponent().foo(action: actionFunction) //-> how do this?
        }
    } 
}

Upvotes: 9

Views: 8422

Answers (1)

Asperi
Asperi

Reputation: 257663

Continuing your approach this might look like below. As alternate it is possible to use ViewModifier protocol.

struct MyComponen: View {
    @Binding var alert: String
    var action: (() -> Void)?
    var body: some View {
        VStack {
            Text("Alert: \(alert)")
            if nil != action {
                Button(action: action!) {
                    Text("Action")
                }
            }
        }
    }
}

extension MyComponen {

    func foo(perform action: @escaping () -> Void ) -> Self {
         var copy = self
         copy.action = action
         return copy
     }
}

struct TestCustomModifier: View {
    @State var message = "state 2"
    var body: some View {
        VStack {
            MyComponen(alert: .constant("state 1"))
            MyComponen(alert: $message).foo(perform: {
                print(">> got action")
            })
        }
    }
}

struct TestCustomModifier_Previews: PreviewProvider {
    static var previews: some View {
        TestCustomModifier()
    }
}

Upvotes: 22

Related Questions