← 返回
未分类 中文

Ios Animation Implementation

Write Swift animation code using Apple's latest frameworks — SwiftUI animations, Core Animation, and UIKit. Prefer first-party APIs over third-party librarie...
使用 Apple 最新框架编写 Swift 动画代码 — SwiftUI 动画、Core Animation 与 UIKit。优先使用第一方 API 而非第三方库...
anderskev anderskev 来源
未分类 clawhub v1.2.1 2 版本 100000 Key: 无需
★ 0
Stars
📥 546
下载
💾 9
安装
2
版本
#latest

概述

iOS Animation Implementation

Write animation code that uses Apple's frameworks directly. Third-party animation libraries add dependency risk and often lag behind new OS releases — Apple's APIs are well-optimized for the render pipeline and get free improvements with each iOS version.

Before Writing Custom Animation

Check whether the system already handles the motion you need. Apple's HIG: "Many system components automatically include motion, letting you offer familiar and consistent experiences throughout your app." System components also automatically adjust for accessibility settings and input methods — Liquid Glass (iOS 26) responds with greater emphasis to direct touch and produces subdued effects for trackpad. Custom animation can't match this adaptiveness for free, so prefer system-provided motion when it exists.

Skip custom animation when:

  • Standard navigation transitions cover your case (push, pop, sheet, fullScreenCover)
  • SF Symbol .symbolEffect provides the feedback you need
  • .contentTransition(.numericText) handles your data change
  • The system's default spring on withAnimation is sufficient

Write custom animation when:

  • The system doesn't provide the spatial relationship you need (hero transitions, custom gestures)
  • You need coordinated multi-property choreography
  • The animation is a signature moment that defines the app's identity
  • Gesture-driven interaction requires custom progress mapping

API Selection

Choose the right API for the job. Start with SwiftUI animations (simplest, most declarative), drop to UIKit when you need interactive control, and reach for Core Animation only when you need layer-level precision.

NeedAPIWhy
----------------
State-driven property changeswithAnimation / .animation(_:value:)Declarative, automatic interpolation
Multi-step sequenced animationPhaseAnimatorDiscrete phases with per-phase timing
Per-property timeline controlKeyframeAnimatorIndependent keyframe tracks per property
Hero transitions between viewsmatchedGeometryEffect + NamespaceGeometry matching across view identity
Navigation push/pop with zoom.navigationTransition(.zoom)iOS 18+ built-in zoom transition
Custom view insertion/removalTransition protocol conformanceTransitionPhase-based modifier
In-view content swap.contentTransition()Numeric text, interpolation, opacity
Scroll-position-based effects.scrollTransitionPhase-driven scroll-linked animation
SF Symbol animation.symbolEffect()Bounce, pulse, wiggle, breathe, rotate
Interactive/interruptible (UIKit)UIViewPropertyAnimatorPause, resume, reverse, scrub
Per-layer property animationCABasicAnimation / CASpringAnimationShadow, border, cornerRadius animation
Complex choreography (layers)CAKeyframeAnimation + CAAnimationGroupMulti-property layer animation
Physics simulationUIDynamicAnimatorGravity, collision, snap, attachment
Haptic feedback paired with animation.sensoryFeedback modifierTied to value changes
Animated background gradientsMeshGradient2D grid of positioned, animated colors

Implementation by Category

Detailed patterns and code examples live in the reference files. Load the one that matches your task:

TaskReference
-----------------
SwiftUI declarative animations (withAnimation, springs, phase, keyframe)references/swiftui-animations.md
View transitions (navigation, modal, custom Transition protocol)references/transitions.md
Gesture-driven interactive animationsreferences/gesture-animations.md
Core Animation and UIKit animation patternsreferences/core-animation.md

When to Load References

  • Writing withAnimation, spring parameters, PhaseAnimator, or KeyframeAnimator → swiftui-animations.md
  • Building navigation transitions, modal presentations, matchedGeometryEffect, or custom Transition → transitions.md
  • Implementing drag-to-dismiss, swipe actions, pinch/rotate, or scroll-linked effects → gesture-animations.md
  • Working with CABasicAnimation, UIViewPropertyAnimator, layer animations, or bridging SwiftUI↔UIKit → core-animation.md

Spring Parameters Quick Reference

Springs are the default animation type in modern SwiftUI. Use duration and bounce — not mass/stiffness/damping unless bridging to UIKit/CA.

PresetDurationBounceUse Case
------------------------------------
.smooth0.50.0Default transitions, most state changes
.snappy0.30.15Micro-interactions, toggles, quick feedback
.bouncy0.50.3Playful moments, attention-drawing
.interactiveSpring0.150.0Gesture tracking, drag following
Customvariesvaries.spring(duration: 0.4, bounce: 0.2)

Accessibility & Multimodal Feedback

Apple's HIG: "Make motion optional" and "supplement visual feedback by also using alternatives like haptics and audio to communicate." Every animation must handle Reduce Motion, and important state changes should use multiple feedback channels — not animation alone.

@Environment(\.accessibilityReduceMotion) private var reduceMotion

// Pattern 1: Conditional animation
withAnimation(reduceMotion ? .none : .spring()) {
    isExpanded.toggle()
}

// Pattern 2: Simplified alternative
.animation(reduceMotion ? .easeOut(duration: 0.15) : .spring(duration: 0.5, bounce: 0.3), value: isActive)

// Pattern 3: Skip entirely
if !reduceMotion {
    view.phaseAnimator(phases) { /* ... */ }
}

Reduce Motion fallback options (from most to least graceful):

  1. Crossfade — replace motion with opacity transition
  2. Shortened — same animation, much faster (0.1–0.15s), no bounce
  3. Instant.animation(.none) or skip the animation block entirely

Cancellation & Interruptibility

Apple's HIG: "Don't make people wait for an animation to complete before they can do anything, especially if they have to experience the animation more than once." Every animation must be interruptible.

  • Spring animations retarget automatically — this is the default and almost always what you want
  • For gesture-driven animations, the user is always in control — let them cancel mid-flight
  • For sequenced animations (KeyframeAnimator, PhaseAnimator with trigger), ensure the UI remains interactive during playback
  • Never disable user interaction during an animation unless there's a critical reason (e.g., destructive action confirmation)

Performance Checklist

  • Animate on the render server when possible — Core Animation runs off the main thread, SwiftUI's drawingGroup() moves rendering to Metal
  • Avoid animating view identity changes (.id() modifier) — this destroys and recreates the view
  • Use geometryGroup() when parent geometry changes cause child layout anomalies during animation
  • Provide explicit shadowPath when animating shadows — without it, the system recalculates the path every frame
  • In lists and scroll views, avoid per-item blur/shadow animations — these cause offscreen rendering for each cell
  • Keep PhaseAnimator and looping animations lightweight — they run continuously
  • For frequent interactions, prefer system-provided animation over custom motion — Apple's HIG: "generally avoid adding motion to UI interactions that occur frequently"
  • Profile with Instruments → "Animation Hitches" template to find frame drops

Gates (before marking work complete)

Run in order; satisfy each Pass before treating the task as done.

  1. API fit — Choose the mechanism from the API Selection table for this task. Pass: You can state in one sentence which “Need” row and API you applied (not a different layer “just because”).
  2. Reduce Motion — Custom timing must follow Accessibility & Multimodal Feedback. Pass: Non-trivial motion branches on accessibilityReduceMotion (or you only used system defaults / no custom timing).
  3. Interruptibility — Matches Cancellation & Interruptibility. Pass: No blanket allowsHitTesting(false) for the whole animation unless the task explicitly requires it and a short comment says why.
  4. Heavy or continuous motion — Loops, PhaseAnimator always-on, per-cell blur/shadow, or other Performance Checklist red flags. Pass: You ran Instruments (Animation Hitches) and captured a note or path to the trace, or you simplified the pattern first and can point to the change.

版本历史

共 2 个版本

  • v1.2.1 当前
    2026-05-03 05:02 安全 安全
  • v1.2.0
    2026-03-30 18:52 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 199 📥 68,371
dev-programming

YouTube

byungkyu
使用托管OAuth集成YouTube Data API,支持搜索视频、管理播放列表、获取频道数据及评论互动,适用于用户需要时使用此技能。
★ 142 📥 42,221
education

Tutorial Docs

anderskev
教程模式——面向学习的指南,通过引导式实践教学。用于编写教程、学习指南、入门指南等。
★ 0 📥 777