我有一个子视图/子视图,它是父视图内实例的模板。该子视图 a 是可由用户在屏幕上移动的圆形。该圆圈的初始拖动应该调用父视图中的函数,该函数会附加子视图的新实例。基本上,最初将圆从其起始位置移动会在该起始位置创建一个新圆。然后,当您最初移动刚刚创建的新圆时,会在该起始位置再次创建另一个新圆,等等......
如何从子视图调用 ContentView 中的 addChild() 函数?
谢谢,我很感激任何帮助。
import SwiftUI
struct ContentView: View {
@State var childInstances: [Child] = [Child(stateBinding: .constant(.zero))]
@State var childInstanceData: [CGSize] = [.zero]
@State var childIndex = 0
func addChild() {
self.childInstanceData.append(.zero)
self.childInstances.append(Child(stateBinding: $childInstanceData[childIndex]))
self.childIndex += 1
}
var body: some View {
ZStack {
ForEach(childInstances.indices, id: \.self) { index in
self.childInstances[index]
}
ForEach(childInstanceData.indices, id: \.self) { index in
Text("y: \(self.childInstanceData[index].height) : x: \(self.childInstanceData[index].width)")
.offset(y: CGFloat((index * 20) - 300))
}
}
}
}
struct …Run Code Online (Sandbox Code Playgroud)