I would like to implement circular dragging in SwiftUI, but am not sure of the best way to go about it.
Here is the basic dragging code - there is one small draggable circle which I would like to limit to the bounds of the bigger one during the updating
phase of the DragGesture. At the moment the black circle is draggable across the entire view.
import SwiftUI
struct ContentView: View {
@State private var position = CGSize.zero
@GestureState var dragOffset: CGSize = .zero
private var dragRadius: CGFloat = 200.0
var body: some View {
ZStack {
Circle()
.fill(Color.red)
.frame(width: dragRadius, height: dragRadius)
Circle()
.fill(Color.black)
.frame(width: dragRadius / 4, height: dragRadius / 4)
.offset(x: position.width + dragOffset.width, y: position.height + dragOffset.height)
.gesture(
DragGesture()
.updating($dragOffset, body: { (value, state, transaction) in
// Need to clamp to circular bounds here??
state = value.translation
})
.onEnded({ (value) in
self.position.height += value.translation.height
self.position.width += value.translation.width
})
)
}
}
}
I wonder whether it's a case of using trigonometry and polar co-ordinates to calculate the distance from the centre and limit to the radius in the direction of the dragged circle, or is there an easier way to get SwiftUI to "see" the circular bounds of a view?