SwiftUI如何使用回调添加自定义修饰符

时间:2019-11-09 14:22:03

标签: ios swift swiftui

在SwiftUI中,您可以编写如下代码:

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

我尝试使用 .onDelete 语法方法向自定义组件添加功能:

struct MyComponen: View {
    @Binding var alert: String

    .
    .
    .
}

我尝试通过扩展添加此功能:

extension MyComponent {

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

    func onDelete() -> Void { 

    }
}

如何更改状态(或使用回调函数):

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 个答案:

答案 0 :(得分:2)

继续您的方法,如下所示。另外,也可以使用ViewModifier协议。

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()
    }
}