In this example we
● use DragGesture to drag green circle toward the red circle
● calculate distance to see how close we were to the red circle when dragging stops
● print different message to the Console depending on the distance
Method onEnded() has trailing Closure which is called when we finish dragging.
Closure is called with Parameter par which holds different information about the dragging.
We are interested in par.location which is CGPoint of cursor position when we stopped dragging.
By calculating distance between par.location CGPoint and destination CGPoint we can see how close we were to red circle
SwiftUI doesn't have Function for calculating distance between two CGPoints so we had to make distanceBetweenPoints()
Drag green circle toward red circle
ContentView.swift
import SwiftUI
//==================================================================================
// VARIABLES
//==================================================================================
var source = CGPoint(x: -100, y:0)
var destination = CGPoint(x: 100, y:0)
var success = "GOOD JOB"
var failure = "NOT CLOSE ENOUGH"
var minimumDistance : CGFloat = 50.0
//==================================================================================
// STRUCT: ContentView
//==================================================================================
struct ContentView : View {
var body : some View {
ZStack {
//SOURCE
Circle()
.fill(Color.green)
.frame(width: 30, height: 30)
.offset(x: source.x, y: source.y)
.gesture( DragGesture()
.onEnded { (value) in //Trailing Closure for body Parameter
let distance = distanceBetweenPoints(destination, value.location)
if (distance < minimumDistance) { print(success) }
else { print(failure) }
})
//DESTINATION
Circle()
.fill(Color.red)
.frame(width: 30, height: 30)
.offset(x: destination.x)