SwiftUI 如何在 C# 中使用“Delegate-EventHandler-EventArgs"方式将数据从子级传递到父级 [英] SwiftUI How to pass data from child to parent as done in C# with the 'Delegate-EventHandler-EventArgs' way
问题描述
我已经阅读了这个主题SwiftUI - 按钮 - 如何将函数(带参数)请求从子进程传递给父进程然而,在原始海报编辑了他自己的答案之后,他提出了一种与他自己的问题不符的方法.不幸的是,我还没有达到足够的分数来在此线程中发表评论
I have already read this thread SwiftUI - Button - How to pass a function (with parameters) request to parent from child however after the original poster edited his own answer he proposed a way that didn't match his own question. Unfortunately I have not yet reached enough points to post comments in this thread
这是上面帖子中重复解释问题的代码示例:
This is the code example from the post above repeated to explain the problem:
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 参数
And now I want to add a String parameter to setViewBackToNil(myStringParameter: String)
推荐答案
这里是可能的解决方案.使用 Xcode 11.4/iOS 13.4 测试
Here is possible solution. Tested with 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"方式将数据从子级传递到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!