我已经阅读过此主题 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 参数
这是可能的解决方案。使用 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)
归档时间: |
|
查看次数: |
1700 次 |
最近记录: |