当涉及协调器时,如何在 SwiftUI 视图与另一个视图之间进行通信? [英] How do I communicate between a SwiftUI view to another when a coordinator is involved?
问题描述
我是 SwiftUI 的新手.刚学几天.我试图找到有关此的教程,但没有成功.
I am new to SwiftUI. Just a few days trying to learn. I have tried to find a tutorial on this but I was not successfull.
假设我有以下观点:
Struct MyPicker: View {
MyPicker
位于 ContentView
内的 VStack
内.我必须从 MyPicker
到 ContentView
传递 3 个参数:color
、width
和 type代码>.
MyPicker
is inside a VStack
inside ContentView
.
I have to pass, from MyPicker
to ContentView
, 3 parameters: color
, width
and type
.
问题是这些值来自 MyPicker
内的委托回调.所以我必须在 MyPicker
里面有一个协调器.
The problem is that these values come from a delegate callback inside MyPicker
. So I have to have a coordinator inside MyPicker
.
struct MyPickerHelper: UIViewRepresentable {
class Coordinator:NSObject, MyPickerDelegate {
var color:UIColor
var width:CGFloat
var type:PKInkingTool.InkType
func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
if toolPicker.selectedTool is PKInkingTool {
let tool = toolPicker.selectedTool as! PKInkingTool
self.color = tool.color
self.width = tool.width
self.type = tool.inkType
}
}
有很多东西,比如@Binding
、@Published
、@State
等等.我该放什么来制作MyPicker传达对 ContentView
的更改?
Theare are a lot of stuff like @Binding
, @Published
, @State
, etc. What do I put where to make MyPicker communicate changes to ContentView
?
推荐答案
您需要将状态作为父视图中的真实来源,并将绑定传递给可表示视图,这...这里是一个参数的示例...
You need to have state as source of truth in parent view and pass binding to it into representable view, which... here is an example for one parameter...
struct MyPicker: View {
@State private var color: UIColor = .clear // << source
var body: some View {
MyPickerHelper(color: $color) // << pass binding
}
}
现在可以表示
struct MyPickerHelper: UIViewRepresentable {
@Binding var color: UIColor
func makeCoordinator() -> Coordinator {
Coordinator(owner: self)
}
...
class Coordinator:NSObject, MyPickerDelegate {
private var owner: MyPickerHelper
init(owner: MyPickerHelper) {
self.owner = owner
}
func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
if toolPicker.selectedTool is PKInkingTool {
let tool = toolPicker.selectedTool as! PKInkingTool
self.owner.color = tool.color // << here update via binding !!!
}
}
...
}
这篇关于当涉及协调器时,如何在 SwiftUI 视图与另一个视图之间进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!