How to: DragGesture in SwiftUI

A quick tutorial on how I built out the Tinder swipe animation using SwiftUI.

Assets.xcassets in Xcode
Asset catalog in Xcode (Assets.xcassets)
import SwiftUIstruct ContentView: View {var body: some View {
// 1
GeometryReader { proxy in
// 2
ZStack {
// 3
CardView(proxy: proxy)
}
}
}
}
struct CardView: View {
// 1
let proxy: GeometryProxy
var body: some View {
// 3
Rectangle()
// 4
.cornerRadius(10)
// 5
.frame(
maxWidth: proxy.size.width - 28,
maxHeight: proxy.size.height * 0.8
)
// 6
.position(
x: proxy.frame(in: .global).midX,
y: proxy.frame(in: .local).midY - 30
)
}
}
struct CardView_Previews: PreviewProvider {
static var previews: some View {
// 2
GeometryReader { proxy in
CardView(proxy: proxy)
}
}
}
Rectangle()
// 1
.overlay(
GeometryReader { proxy in
// 2
ZStack {
// 3
Image("me")
.resizable()
.aspectRatio(contentMode: .fill)
.clipped()
// 4
VStack(alignment: .leading) {
// 5
Text("Gary")
.foregroundColor(.white)
.fontWeight(.bold)
Text("iOS Dev")
.foregroundColor(.white)
.fontWeight(.bold)
}
// 6
.position(
x: proxy.frame(in: .local).minX + 75,
y: proxy.frame(in: .local).maxY - 50
)
}
}
)
// var body ...
// 1
let dragGesture = DragGesture()

Rectangle()
.overlay()
...
// 2
.gesture(dragGesture)
// 3
.animation(.interactiveSpring())
// 2
@GestureState var translation: CGSize = .zero
var body: some View {
let dragGesture = DragGesture()
// 1
.updating($translation) { (value, state, _) in
// 3
state = value.translation
}
// Add to Rectangle()// 1
.offset(x: translation.width, y: 0)
.gesture(dragGesture)
// ...
// 1
@GestureState var degrees: Double = 0

var body: some View {
let dragGesture = DragGesture()
.updating($translation) { (value, state, _) in
state = value.translation
}
// 2
.updating($degrees) { (value, state, _) in
// 3
state = value.translation.width > 0 ? 2 : -2
}
// 1
.rotationEffect(.degrees(degrees))
Tinder swipe animation in Xcode
Tinder swipe animation in Xcode
Tinder card animation in Xcode

Shameless plug: If you enjoyed this tutorial get part two on my on Patreon in video form or the link below

PS. follow for more tutorials 😎

iOS Software Engineer ⚡️ Creator

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store