Communitygithub.com

ComeOnOliver/skillshub

SwiftUI ジェスチャー(タップ、ドラッグ、長押し、ズーム、回転)の実装、ジェスチャー合成、状態管理、競合解決、アクセシビリティ、およびクロスプラットフォーム対応に関する包括的なパターンを提供します。

skillshub とは?

このスキルは、SwiftUI におけるジェスチャー認識、合成、状態管理、アクセシビリティ統合に関する包括的なガイドです。タップ、ドラッグ、長押し、ズーム、回転などの基本ジェスチャーから、`.simultaneously`、`.sequenced`、`.exclusively` を使用した複数ジェスチャーの合成パターンまでをカバーします。また、`@GestureState` と `@State` の適切な使い分け、カスタムジェスチャーの作成、Velocity や予測終了位置の活用、VoiceOver 対応やキーボード代替操作によるアクセシビリティの確保、iOS・macOS・visionOS 間のクロスプラットフォーム考慮事項についても詳しく説明します。開発者は、このガイドを参照することで、ジェスチャーの競合解決や状態管理の問題をデバッグし、ユーザーフレンドリーでアクセシブルなインタラクションを実装できます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-gestures

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

SwiftUI ジェスチャー

SwiftUI におけるジェスチャー認識、合成パターン、状態管理、アクセシビリティ統合に関する包括的なガイド。

このスキルを使用するタイミング

  • タップ、ドラッグ、長押し、ズーム、回転のジェスチャーを実装する場合
  • 複数のジェスチャーを合成する場合(同時、順次、排他的)
  • GestureState でジェスチャーの状態を管理する場合
  • カスタムジェスチャー認識を作成する場合
  • ジェスチャーの競合や応答しないジェスチャーをデバッグする場合
  • VoiceOver でジェスチャーをアクセシブルにする場合
  • クロスプラットフォーム(iOS、macOS、visionOS)でジェスチャーを処理する場合

プロンプト例

開発者が実際に尋ねる、このスキルが回答できるように設計された質問の例:

1. 「ドラッグジェスチャーが機能しません。ビューをドラッグしても動きません。どうデバッグすればいいですか?」

→ このスキルでは、DragGesture の状態管理パターンと、@GestureState を使用してビューのオフセットを適切に更新する方法を説明します

2. 「同じビューにタップジェスチャーとドラッグジェスチャーの両方があります。タップは機能しますが、ドラッグは機能しません。どう修正すればいいですか?」

→ このスキルでは、.simultaneously、.sequenced、.exclusively を使用したジェスチャー合成による競合解決方法を示します

3. 「ユーザーがアイテムをドラッグする前に長押しするようにしたいです。ジェスチャーをどう連鎖させればいいですか?」

→ このスキルでは、LongPressGesture と DragGesture を正しい順序で組み合わせるための .sequenced パターンを示します

4. 「ジェスチャーが終了してもジェスチャーの状態がリセットされません。ビューが間違った位置に留まります。」

→ このスキルでは、@GestureState の自動リセット動作と、適切な状態管理のための updating パラメータについて説明します

5. 「VoiceOver ユーザーがジェスチャーを必要とする機能にアクセスできません。どうすればジェスチャーをアクセシブルにできますか?」

→ このスキルでは、.accessibilityAction パターンと、VoiceOver ユーザーに代替操作を提供する方法を示します


適切なジェスチャーの選択(決定木)

必要な操作は何ですか?

├─ シングルタップ/クリック?
│  └─ Button(推奨)または TapGesture を使用
│
├─ ドラッグ/パン移動?
│  └─ DragGesture を使用
│
├─ アクション前に長押し?
│  └─ LongPressGesture を使用
│
├─ ピンチでズーム?
│  └─ MagnificationGesture を使用
│
├─ 2本指で回転?
│  └─ RotationGesture を使用
│
├─ 複数のジェスチャーを同時に?
│  ├─ 両方を同時に? → .simultaneously
│  ├─ 順番に? → .sequenced
│  └─ どちらか一方? → .exclusively
│
└─ 複雑なカスタム動作?
   └─ Gesture プロトコルに準拠したカスタムジェスチャーを作成

パターン 1: 基本的なジェスチャー認識

TapGesture

❌ 間違い(セマンティックビューではないカスタムタップ)

Text("送信")
  .onTapGesture {
    submitForm()
  }

問題点:

  • VoiceOver にボタンとして通知されない
  • 視覚的な押下フィードバックがない
  • アクセシビリティ設定を尊重しない

✅ 正しい(タップアクションには Button を使用)

Button("送信") {
  submitForm()
}
.buttonStyle(.bordered)

TapGesture を使用するタイミング: タップのデータ(位置、回数)や標準的でないタップ動作が必要な場合のみ:

Image("map")
  .onTapGesture(count: 2) { // ダブルタップで詳細表示
    showDetails()
  }
  .onTapGesture { location in // シングルタップでピン留め
    addPin(at: location)
  }

DragGesture

❌ 間違い(ジェスチャー内での直接的な状態変更)

@State private var offset = CGSize.zero

var body: some View {
  Circle()
    .offset(offset)
    .gesture(
      DragGesture()
        .onChanged { value in
          offset = value.translation // ❌ 毎フレーム更新され、カクつきの原因に
        }
    )
}

問題点:

  • 全てのドラッグイベント(毎秒60〜120回)でビューが更新される
  • 元の位置にリセットする方法がない
  • ドラッグがキャンセルされた場合に中間状態が失われる

✅ 正しい(一時的な状態には GestureState を使用)

@GestureState private var dragOffset = CGSize.zero
@State private var position = CGSize.zero

var body: some View {
  Circle()
    .offset(x: position.width + dragOffset.width,
            y: position.height + dragOffset.height)
    .gesture(
      DragGesture()
        .updating($dragOffset) { value, state, _ in
          state = value.translation // ドラッグ中の一時的な状態
        }
        .onEnded { value in
          position.width += value.translation.width // 最終位置を確定
          position.height += value.translation.height
        }
    )
}

理由: GestureState はジェスチャー終了時に自動的に初期値にリセットされ、状態の破損を防ぎます。


LongPressGesture

@GestureState private var isDetectingLongPress = false
@State private var completedLongPress = false

var body: some View {
  Text("長押ししてください")
    .foregroundStyle(isDetectingLongPress ? .red : .blue)
    .gesture(
      LongPressGesture(minimumDuration: 1.0)
        .updating($isDetectingLongPress) { currentState, gestureState, _ in
          gestureState = currentState // 押下中の視覚的フィードバック
        }
        .onEnded { _ in
          completedLongPress = true // 長押し後のアクション
        }
    )
}

主要パラメータ:

  • minimumDuration: 押し続ける時間(デフォルト 0.5 秒)
  • maximumDistance: キャンセル前に指が動ける最大距離(デフォルト 10 ポイント)

MagnificationGesture

@GestureState private var magnificationAmount = 1.0
@State private var currentZoom = 1.0

var body: some View {
  Image("photo")
    .scaleEffect(currentZoom * magnificationAmount)
    .gesture(
      MagnificationGesture()
        .updating($magnificationAmount) { value, state, _ in
          state = value.magnification
        }
        .onEnded { value in
          currentZoom *= value.magnification
        }
    )
}

プラットフォーム注意事項:

  • iOS: 2本指のピンチジェスチャー
  • macOS: トラックパッドのピンチ
  • visionOS: 3D空間でのピンチジェスチャー

RotationGesture

@GestureState private var rotationAngle = Angle.zero
@State private var currentRotation = Angle.zero

var body: some View {
  Rectangle()
    .fill(.blue)
    .frame(width: 200, height: 200)
    .rotationEffect(currentRotation + rotationAngle)
    .gesture(
      RotationGesture()
        .updating($rotationAngle) { value, state, _ in
          state = value.rotation
        }
        .onEnded { value in
          currentRotation += value.rotation
        }
    )
}

パターン 2: ジェスチャー合成

同時ジェスチャー

使用するタイミング: 2つのジェスチャーを同時に機能させたい場合

@GestureState private var dragOffset = CGSize.zero
@GestureState private var magnificationAmount = 1.0

var body: some View {
  Image("photo")
    .offset(dragOffset)
    .scaleEffect(magnificationAmount)
    .gesture(
      DragGesture()
        .updating($dragOffset) { value, state, _ in
          state = value.translation
        }
        .simultaneously(with:
          MagnificationGesture()
            .updating($magnificationAmount) { value, state, _ in
              state = value.magnification
            }
        )
    )
}

ユースケース: ドラッグとピンチズームを同時に行える写真ビューア。


順次ジェスチャー

使用するタイミング: 一方のジェスチャーが完了してから次のジェスチャーを開始させたい場合

@State private var isLongPressing = false
@GestureState private var dragOffset = CGSize.zero

var body: some View {
  Circle()
    .offset(dragOffset)
    .gesture(
      LongPressGesture(minimumDuration: 0.5)
        .onEnded { _ in
          isLongPressing = true
        }
        .sequenced(before:
          DragGesture()
            .updating($dragOffset) { value, state, _ in
              state = value.translation
            }
            .onEnded { _ in
              isLongPressing = false
            }
        )
    )
}

ユースケース: iOSのホーム画面 — 長押しで編集モードに入り、その後ドラッグで並べ替え。


排他的ジェスチャー

使用するタイミング: どちらか一方のジェスチャーのみを有効にしたい場合

var body: some View {
  Rectangle()
    .gesture(
      TapGesture(count: 2) // ダブルタップ
        .onEnded { _ in
          zoom()
        }
        .exclusively(before:
          TapGesture(count: 1) // シングルタップ
            .onEnded { _ in
              select()
            }
        )
    )
}

理由: .exclusively がないと、ダブルタップがシングルタップとダブルタップの両方のハンドラをトリガーします。

仕組み: SwiftUI は2回目のタップが来るのを待ちます。来た場合 → ダブルタップが優先。来なかった場合 → シングルタップが優先。


パターン 3: GestureState vs State

それぞれの使用タイミング

ユースケース状態の種類理由
ジェスチャー中の一時的なフィードバック@GestureStateジェスチャー終了時に自動リセット
最終的な確定値@Stateジェスチャー後も保持
ジェスチャー中のアニメーション@GestureStateスムーズな遷移
データの永続化@Stateビュー更新後も維持

完全な例: ドラッグ可能なカード

struct DraggableCard: View {
  @GestureState private var dragOffset = CGSize.zero // 一時的
  @State private var position = CGSize.zero          // 永続的

  var body: some View {
    RoundedRectangle(cornerRadius: 12)
      .fill(.blue)
      .frame(width: 300, height: 200)
      .offset(
        x: position.width + dragOffset.width,
        y: position.height + dragOffset.height
      )
      .gesture(
        DragGesture()
          .updating($dragOffset) { value, state, transaction in
            state = value.translation

            // スムーズなフィードバックのためのアニメーションを有効化
            transaction.animation = .interactiveSpring()
          }
          .onEnded { value in
            // アニメーション付きで最終位置を確定
            withAnimation(.spring()) {
              position.width += value.translation.width
              position.height += value.translation.height
            }
          }
      )
  }
}

重要なポイント: GestureState の第3パラメータ transaction を使用すると、ジェスチャー中のアニメーションをカスタマイズできます。


パターン 4: カスタムジェスチャー

カスタムジェスチャーを作成するタイミング

  • 組み込みジェスチャーで提供されていないジェスチャー動作が必要
  • 複雑なジェスチャーロジックをカプセル化したい
  • 複数のビューでジェスチャーを再利用したい

例: 方向を認識するスワイプジェスチャー

struct SwipeGesture: Gesture {
  enum Direction {
    case left, right, up, down
  }

  let minimumDistance: CGFloat
  let coordinateSpace: CoordinateSpace

  init(minimumDistance: CGFloat = 50, coordinateSpace: CoordinateSpace = .local) {
    self.minimumDistance = minimumDistance
    self.coordinateSpace = coordinateSpace
  }

  // Value は方向
  typealias Value = Direction

  // Body は DragGesture を基に構築
  var body: AnyGesture<Direction> {
    DragGesture(minimumDistance: minimumDistance, coordinateSpace: coordinateSpace)
      .map { value in
        let horizontal = value.translation.width
        let vertical = value.translation.height

        if abs(horizontal) > abs(vertical) {
          return horizontal < 0 ? .left : .right
        } else {
          return vertical < 0 ? .up : .down
        }
      }
      .eraseToAnyGesture()
  }
}

// 使用例
Text("スワイプしてください")
  .gesture(
    SwipeGesture()
      .onEnded { direction in
        switch direction {
        case .left: deleteItem()
        case .right: archiveItem()
        default: break
        }
      }
  )

パターン 5: ジェスチャーの速度と予測

速度へのアクセス

@State private var velocity: CGSize = .zero

var body: some View {
  Circle()
    .gesture(
      DragGesture()
        .onEnded { value in
          // iOS 18+ では value.velocity は非推奨
          // value.predictedEndLocation と時間を使用

          let timeDelta = value.time.timeIntervalSince(value.startLocation.time)
          let distance = value.translation

          velocity = CGSize(
            width: distance.width / timeDelta,
            height: distance.height / timeDelta
          )

          // 慣性を伴うアニメーション
          withAnimation(.interpolatingSpring(stiffness: 100, damping: 15)) {
            applyMomentum(velocity: velocity)
          }
        }
    )
}

予測終了位置(iOS 16+)

DragGesture()
  .onChanged { value in
    // 速度に基づいてジェスチャーが終了する可能性が高い位置
    let predicted = value.predictedEndLocation

    // アイテムが着地する位置のプレビューを表示
    showPreview(at: predicted)
  }

ユースケース: 弾性物理、慣性スクロール、スローアニメーション。


パターン 6: アクセシビリティ統合

カスタムジェスチャーをアクセシブルにする

❌ 間違い(ジェスチャーのみ、VoiceOver 非対応)

Image("slider")
  .gesture(
    DragGesture()
      .onChanged { value in
        updateVolume(value.translation.width)
      }
  )

問題点: VoiceOver ユーザーがスライダーを調整できない。

✅ 正しい(アクセシビリティアクションを追加)

@State private var volume: Double = 50

var body: some View {
  Image("slider")
    .gesture(
      DragGesture()
        .onChanged { value in
          volume = calculateVolume(from: value.translation.width)
        }
    )
    .accessibilityElement()
    .accessibilityLabel("音量")
    .accessibilityValue("\(Int(volume))%")
    .accessibilityAdjustableAction { direction in
      switch direction {
      case .increment:
        volume = min(100, volume + 5)
      case .decrement:
        volume = max(0, volume - 5)
      @unknown default:
        break
      }
    }
}

理由: VoiceOver ユーザーは、ジェスチャーを見たり使用したりしなくても、スワイプアップ/ダウンで音量を調整できるようになります。

キーボード代替操作(macOS)

Rectangle()
  .gesture(
    DragGesture()
      .onChanged { value in
        move(by: value.translation)
      }
  )
  .onKeyPress(.upArrow) {
    move(by: CGSize(width: 0, height: -10))
    return .handled
  }
  .onKeyPress(.downArrow) {
    move(by: CGSize(width: 0, height: 10))
    return .handled
  }
  .onKeyPress(.leftArrow) {
    move(by: CGSize(width: -10, height: 0))
    return .handled
  }
  .onKeyPress(.rightArrow) {
    move(by: CGSize(width: 10, height: 0))
    return .handled
  }

パターン 7: クロスプラットフォームのジェスチャー

iOS vs macOS vs visionOS

ジェスチャーiOSmacOSvisionOS
TapGesture指のタップマウスクリックエアタップ
DragGesture1本指のドラッグトラックパッドドラッグ直接操作(ドラッグ)
LongPressGesture長押しマウス長押し長押しエアタップ
MagnificationGesture2本指ピンチトラックパッドピンチ3Dピンチ
RotationGesture2本指回転トラックパッド回転3D回転

プラットフォーム間での一貫した動作:

  • 基本のGestureStateパターンは全てのプラットフォームで同じ
  • アクセシビリティの追加はiOSとmacOSの両方で必須
  • visionOSは onChanged と onEnded で空間位置を使用

パターン 8: デバッグとパフォーマンス

ジェスチャーのログ出力

struct GestureDebugView: View {
  @GestureState private var dragOffset = CGSize.zero
  @State private var debugLog: [String] = []

  var body: some View {
    VStack {
      Circle()
        .offset(dragOffset)
        .gesture(
          DragGesture()
            .updating($dragOffset) { value, state, _ in
              state = value.translation
              log("ドラッグ中: \(value.translation)")
            }
            .onEnded { value in
              log("ドラッグ終了: \(value.translation)")
            }
        )

      ScrollView {
        ForEach(debugLog.reversed(), id: \.self) { entry in
          Text(entry).font(.caption)
        }
      }
    }
  }

  private func log(_ message: String) {
    debugLog.append("[\(Date().timeIntervalSince1970)] \(message)")
  }
}

よくある問題と解決策

問題原因解決策
ジェスチャーが認識されない競合するジェスチャー排他的/同時修飾子を確認
ジェスチャーが途中でキャンセルされるmaximumDistance が小さすぎる値を大きくする
ドラッグがカクつく@Stateの直接更新@GestureStateを使用
VoiceOverが動作しないアクセシビリティアクションの欠落.accessibilityAdjustableActionを追加
macOSでジェスチャーが反応しないキーボードフォーカスがない.focusable() を追加

まとめ

重要なポイント

  1. @GestureState は一時的なジェスチャー状態に使用し、自動リセットを活用する
  2. @State は確定した値に使用し、ジェスチャー後も保持する
  3. Gesture Composition(.simultaneously、.sequenced、.exclusively)で競合を解決する
  4. アクセシビリティアクション を常に追加し、VoiceOverユーザーをサポートする
  5. クロスプラットフォーム の違いを理解し、それに応じて実装する
  6. カスタムジェスチャーはGestureプロトコルに準拠して作成する
  7. 速度と予測 を使用して、自然なインタラクションを実現する
  8. デバッグログ は問題の診断に役立つ

関連するAppleドキュメント


このガイドはAppleのドキュメントに基づいており、iOS 17+、macOS 14+、visionOS 1+ のパターンに焦点を当てています。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

関連スキル