.gesture Modifier allows View to react to different Gestures.
Syntax
.gesture( TapGesture ().onEnded({ print("TAP" ) }) )
.gesture( LongPressGesture ().onEnded({ value in print("Event ended = \(value )" ) }) )
.gesture( DragGesture ().onEnded({ value in print("Value = \(value )" ) }) )
.gesture( MagnificationGesture().onEnded({ value in print("Magnification = \(value )" ) }) )
Tap (Alternative is .onTapGesture)
.gesture( TapGesture()
.onEnded {
self.color.toggle()
}
)
Long Press (Alternative is .onLongPressGesture)
.gesture( LongPressGesture(minimumDuration: 1, maximumDistance: 1)
.onEnded { value in //Always true
self.color.toggle()
}
)
Drag (Closure Input Parameter holds start and end location CGPoints)
@GestureState private var dragOffset = CGSize.zero
@State private var finalOffset = CGSize.zero
.gesture( DragGesture()
.updating($dragOffset) { (value, state, transaction) in //Trailing Closure for body Parameter
state = value.translation //location - startLocation
}
.onEnded { (value) in //Trailing Closure for _ action Parameter
self.finalOffset = value.translation //Works only for the first drag
}
)
Magnification (Hold Option key to simulate Magnification while dragging Left Mouse Button)
@GestureState var magnification : CGFloat = 0
@State var finalMagnification : CGFloat = 0
.gesture( MagnificationGesture()
.updating($magnification ) { (value, state, transaction) in //Trailing Closure for body Parameter
if value.isFinite { state = value } //Amount of magnification
}
.onEnded { (value) in
if value.isFinite { self.finalMagnification = value }
}
)