9

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?
        }
    } 
}

1 Answer 1

22

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()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.