'SwiftUI - Snapshot a variable as a value instead of a pointer so it is not updated during DragGesture .onchanged lifecycle
I am trying to move a CGPoint (greenPoint) by moving another one (bluePoint). The distance and angle must remained the same. In order to capture that, I store the x delta as adjacent and y delta as opposite. My issue is that when I move the blue point, the adjacent and opposite values get updated and therefore the greenPoint stays in the same place. I was thinking I could maybe take a snapshot of the values before the .onChanged, but can’t work out how? Code is below.
Circle()
.strokeBorder(.white, lineWidth: 2)
.background(Circle().fill(.blue))
.frame(width:10, height:10)
.position(bluePoint)
.gesture(DragGesture()
.onChanged{state in
greenPoint = CGPoint(x: bluePoint.x+adjacent, y: bluePoint.y+opposite)
bluePoint = state.location
})
Note: I need to keep adjacent and opposite as variables rather than static values, because in another part of the code moving the greenPoint is permitted while the bluePoint stays still.
Thanks!
Solution 1:[1]
Thanks for the suggestions. Got it to work with the following:
let adj = baseCoords.adjacent
let op = baseCoords.opposite
…
Circle()
.strokeBorder(.white, lineWidth:2)
.background(Circle().fill(.blue))
.frame(width:12, height:12)
.position(bluePoint)
.gesture(DragGesture()
.onChanged{state in
bluePoint = state.location
greenPoint.x = bluePoint.x + adj
greenPoint.y = bluePoint.y + op
}
)
By copying into 2 new variables, the adj and op values do not update during the .onChanged.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris F |
