SwiftUI Gestures

SwiftUI Gestures

Handle taps, drags, and other interactions with .gesture and built-in gesture recognizers.


Tap and Long Press

Handle taps and long presses with .onTapGesture and .onLongPressGesture.


Syntax:

  • .onTapGesture { ... }
  • .onLongPressGesture(minimumDuration:perform:)

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct TapLongPressDemo: View {
  @State private var on = false
  @State private var pressed = false
  var body: some View {
Circle()
  .fill(on ? .green : .gray)
  .frame(width: 80, height: 80)
  .scaleEffect(pressed ? 0.9 : 1)
  .onTapGesture { on.toggle() }
  .onLongPressGesture(minimumDuration: 0.5) { pressed.toggle() }
} }

This example toggles color on tap and briefly scales the circle on a long-press.


DragGesture

Track finger movement by attaching a DragGesture to update an offset.

Syntax: .gesture(DragGesture().onChanged { value in ... }.onEnded { ... })

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct DragDemo: View {
  @State private var offset: CGSize = .zero
  var body: some View {
Text("Drag me")
  .padding(12)
  .background(.blue.opacity(0.1))
  .cornerRadius(8)
  .offset(offset)
  .gesture(
    DragGesture()
      .onChanged { value in offset = value.translation }
      .onEnded { _ in withAnimation(.spring()) { offset = .zero } }
  )
} }

This example follows the finger while dragging and springs back to the origin on release.



Combining Gestures

Use .simultaneousGesture or .highPriorityGesture to coordinate multiple gestures.

Syntax:

  • .simultaneousGesture(TapGesture())
  • .highPriorityGesture(DragGesture())

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct CombineGesturesDemo: View {
  @State private var tapped = 0
  @State private var dragged = false
  var body: some View {
Rectangle()
  .fill(dragged ? .orange : .purple)
  .frame(height: 120)
  .overlay(Text("taps: \(tapped)"))
  .simultaneousGesture(TapGesture().onEnded { tapped += 1 })
  .highPriorityGesture(DragGesture().onChanged { _ in dragged = true }.onEnded { _ in dragged = false })
} }

This example counts taps while also reacting to drags, demonstrating gesture composition.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *