Answers for "add callbacks to view swiftui"

0

add callbacks to view swiftui

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()
    }
}
Posted by: Guest on January-24-2021

Code answers related to "Swift"

Browse Popular Code Answers by Language