I have a child/subview which is a template for instances inside the parent view. This child view a is circle that can be moved around the screen by the user. The initial drag of this circle is supposed to call a function in the parent view, which appends a new instance of the child view. Basically, initially moving the circle from its starting position creates a new circle in that start position. Then when you initially move that new one, which was just created, another new circle is created at that starting position again, etc...
How do I call the addChild() function that's in ContentView from the Child view?
Thank you, I appreciate any help.
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 ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
struct Child: View {
@Binding var stateBinding: CGSize
@State var isInitalDrag = true
@State var isOnce = true
@State var currentPosition: CGSize = .zero
@State var newPosition: CGSize = .zero
var body: some View {
Circle()
.frame(width: 50, height: 50)
.foregroundColor(.blue)
.offset(self.currentPosition)
.gesture(
DragGesture()
.onChanged { value in
if self.isInitalDrag && self.isOnce {
// Call function in ContentView here... How do I do it?
ContentView().addChild()
self.isOnce = false
}
self.currentPosition = CGSize(
width: CGFloat(value.translation.width + self.newPosition.width),
height: CGFloat(value.translation.height + self.newPosition.height)
)
self.stateBinding = self.currentPosition
}
.onEnded { value in
self.newPosition = self.currentPosition
self.isOnce = true
self.isInitalDrag = false
}
)
}
}
struct Child_Previews: PreviewProvider {
static var previews: some View {
Child(stateBinding: .constant(.zero))
}
}