Communitygithub.com

SwiftUI 手势识别

在实现 SwiftUI 手势(轻点、拖拽、长按、缩放、旋转)、组合手势、管理手势状态或调试手势冲突时使用——提供手势识别、组合、可访问性及跨平台支持的全面模式。

SwiftUI 手势识别 是什么?

该技能提供了在 SwiftUI 应用程序中实现手势识别、组合和状态管理的全面模式。它涵盖了从 TapGesture、DragGesture、LongPressGesture、MagnificationGesture 到 RotationGesture 的所有内置手势,并提供了如何使用 `.simultaneously`、`.sequenced` 和 `.exclusively` 来组合多个手势的详细示例。技能解释了 `@GestureState` 与 `@State` 之间的关键区别,确保手势状态在结束时正确重置,并展示了如何通过 `transaction` 参数在手势期间启用流畅动画。除了基本用法,该技能还深入探讨了高级主题,如创建遵循 `Gesture` 协议的自定义手势、利用预测结束位置实现基于动量的动画、通过与 VoiceOver 的 `.accessibilityAdjustableAction` 集成以及为 macOS 提供键盘替代方案来使手势变得可访问,以及处理 iOS、macOS 和 visionOS 之间的跨平台差异。它包含一个决策树,用于根据所需交互选择正确的手势,并且由已经解决常见问题(如手势冲突、状态重置和 VoiceOver 支持)的开发者提出的真实示例提示所驱动。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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
│
├─ 双指旋转?
│  └─ 使用 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(\

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

相关技能