SwiftUI 如何使用 C# 中的“Delegate-EventHandler-EventArgs”方式将数据从子级传递到父级

Rol*_*idt 2 swift swiftui

我已经阅读过此主题 SwiftUI - Button - How to pass a function (withparameters) request to Parent from child 但是在原始发布者编辑了自己的答案后,他提出了一种与他自己的问题不匹配的方法。不幸的是,我还没有达到足够的分数来在此线程中发表评论

这是上面帖子中重复解释问题的代码示例:

struct ChildView: View {
    var function: () -> Void

    var body: some View {
        Button(action: {
            self.function()
        }, label: {
            Text("Button")
        })
    }
}

struct ContentView: View {
    var body: some View {
        ChildView(function: { self.setViewBackToNil() })
    }

    func setViewBackToNil() {
        print("I am the parent")
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想向 setViewBackToNil(myStringParameter: String) 添加一个 String 参数

Asp*_*eri 5

这是可能的解决方案。使用 Xcode 11.4 / iOS 13.4 进行测试

struct ChildView: View {
    var function: (String) -> Void

    @State private var value = "Child Value"
    var body: some View {
        Button(action: {
            self.function(self.value)
        }, label: {
            Text("Button")
        })
    }
}

struct ContentView: View {
    var body: some View {
        ChildView { self.setViewBackToNil(myStringParameter: $0) }
    }

    func setViewBackToNil(myStringParameter: String) {
        print("I am the parent: \(myStringParameter)")
    }
}
Run Code Online (Sandbox Code Playgroud)