我已经读过这个帖子了 SwiftUI - Button - How to pass a function (with parameters) 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")
}
}
现在我想向 setViewBackToNil(myStringParameter: String) 添加一个 String 参数
最佳答案
这是可能的解决方案。使用 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)")
}
}
关于SwiftUI 如何使用 C# 中的 'Delegate-EventHandler-EventArgs' 方式将数据从子级传递到父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62279653/