Communitygithub.com

UIKit 动画调试

当 CAAnimation 完成处理程序不触发、弹簧物理效果在设备上看起来异常、动画时长与实际不符、手势与动画交互导致卡顿,或模拟器与真实硬件之间存在时间差异时,使用本技能进行系统化 CAAnimation 诊断,涵盖 CATransaction 模式、帧率感知和设备特定行为。

UIKit 动画调试 是什么?

本技能提供了一个系统化的调试方法,专门用于解决 UIKit 中 Core Animation 常见的问题,例如完成处理程序不触发、动画时长不匹配、弹簧物理效果异常以及手势与动画交互卡顿等。其核心原则是,90% 的 CAAnimation 问题源于 CATransaction 时机、图层状态或帧率假设,而不是 Core Animation 本身的 Bug。 技能详细描述了必须优先执行的诊断步骤,包括检查完成处理程序是否触发、实际动画时长、当前活跃的动画以及图层状态等。它提供了一个决策树,帮助开发者根据具体症状(如完成处理程序仅在模拟器上触发、时长不匹配、手势+动画卡顿等)选择正确的解决方案。 该技能列出了 7 种常见模式,并强调必须按顺序逐一应用,禁止同时尝试多个模式。这些模式涵盖了完成处理程序设置时机、CATransaction 对动画时长的覆盖、`isRemovedOnCompletion` 与 `fillMode` 的正确使用、在完成处理程序中强制使用 `[weak self]` 以避免循环引用、多个动画使用相同 keyPath 时的冲突处理、使用 CADisplayLink 同步手势与动画更新,以及根据设备性能类(而非型号)调整弹簧动画参数。 最后,技能提供了一个快速参考表,列出了常见问题、检查点和修复方案。如果按照所有步骤操作后问题仍然存在(超过30分钟),则建议必须使用 Instruments 的 Core Animation 工具进行性能分析,并禁止使用硬编码或临时解决方案。

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

在你喜欢的 AI 中提问

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

文档

UIKit 动画调试 是做什么的?

概述

CAAnimation 问题表现为完成处理程序缺失、动画时长错误或在特定条件下出现卡顿。核心原则:90% 的 CAAnimation 问题源于 CATransaction 时机、图层状态或帧率假设,而非 Core Animation 本身的 Bug。

危险信号 — 怀疑是 CAAnimation 问题

如果你看到以下任何一个现象,应该怀疑是动画逻辑而非设备行为:

  • 完成处理程序在模拟器上触发,但在设备上不触发
  • 动画声明时长(如 0.5 秒)与实际可视时长(如 1.2 秒)不符
  • 弹簧动画在 iPhone 15 Pro 上效果正常,但在旧设备上卡顿
  • 手势和动画同时使用时出现卡顿(分开时正常)
  • 在完成处理程序中使用了 [weak self] 但不确定其作用
  • ❌ 禁止 硬编码时长或数值来“匹配实际表现”
    • 这会将设备特定的 Bug 带给使用不同硬件的用户
    • 不要将其合理化,认为是“临时修复”或“足够好”

关键区别:模拟器通常隐藏了时序问题(仅 60Hz,无节流)。真实设备会暴露它们(可变帧率、CPU 节流、后台压力)。强制要求:在发货前,必须在真实设备(支持的最低调型号)上进行测试。

强制优先步骤

始终优先执行以下步骤(在修改代码之前):

// 1. 检查完成处理程序是否触发
animation.completion = { [weak self] finished in
    print("🔥 完成处理程序已触发:finished=\(finished)")
    guard let self = self else {
        print("🔥 self 为 nil")
        return
    }
    // 原始代码
}

// 2. 检查实际时长与声明时长是否一致
let startTime = Date()
let anim = CABasicAnimation(keyPath: "position.x")
anim.duration = 0.5  // 声明时长
layer.add(anim, forKey: "test")

DispatchQueue.main.asyncAfter(deadline: .now() + 0.51) {
    print("经过时长:\(Date().timeIntervalSince(startTime))")  // 实际时长
}

// 3. 检查当前哪些动画处于活动状态
if let keys = layer.animationKeys() {
    print("活跃的动画:\(keys)")
    for key in keys {
        if let anim = layer.animation(forKey: key) {
            print("\(key):duration=\(anim.duration), removed=\(anim.isRemovedOnCompletion)")
        }
    }
}

// 4. 检查图层状态
print("图层速度:\(layer.speed)")  // != 1.0 表示时序被缩放
print("图层时间偏移:\(layer.timeOffset)")  // != 0 表示动画有偏移

这告诉你什么

  • 完成处理程序输出出现 → 处理程序已触发,问题在回调代码中
  • 完成处理程序输出缺失 → 处理程序未触发,检查 CATransaction/图层状态
  • 经过时长 == 声明时长 → 时长正确,视觉卡顿来自帧率
  • 经过时长 != 声明时长 → CATransaction 包装正在改变时长
  • layer.speed != 1.0 → 有东西正在减慢动画
  • 活跃的动画列表很长 → 多个动画在竞争

强制解释

在修改任何代码之前,你必须确定哪一个诊断是根本原因:

  1. 如果完成处理程序触发但经过时长 != 声明时长 → 应用模式 2 (CATransaction)
  2. 如果完成处理程序未触发且 isRemovedOnCompletion 为 true → 应用模式 3
  3. 如果完成处理程序触发但视觉效果卡顿 → 必须优先使用 Instruments 进行分析
    • 您不能猜测“可能是帧率问题”——用数据证明
    • Profile > Core Animation 工具可以确定地显示帧率下降
    • 如果你跳过 Instruments,你就是在猜测

如果诊断结果矛盾或不清晰

  • 停止。不要继续应用模式
  • 添加更多 print 语句来缩小原因范围
  • 问问自己:“诊断结果显示 X 和 Y,但 Z 不匹配。我遗漏了什么?”
  • 如果不确定,使用 Instruments > Core Animation 进行分析

决策树

CAAnimation 问题?
├─ 完成处理程序从未触发?
│  ├─ 仅在模拟器上?
│  │  └─ 模拟器时序不同(60Hz)。在真实设备上测试。
│  ├─ 仅在真实设备上?
│  │  ├─ 检查:isRemovedOnCompletion 和 fillMode
│  │  ├─ 检查:CATransaction 包装
│  │  └─ 检查:动画期间应用是否进入后台
│  └─ 在模拟器和设备上都有?
│     ├─ 检查:完成处理程序是否在添加动画之前设置
│     └─ 检查:[weak self] 是否确实被捕获(在完成前不为 nil)
│
├─ 时长不匹配(声明时长 != 视觉时长)?
│  ├─ `layer.speed != 1.0`?
│  │  └─ 有东西缩放了动画时长。找到并修复。
│  ├─ 动画是否包装在 CATransaction 中?
│  │  └─ `CATransaction.setAnimationDuration()` 会覆盖 `animation.duration`
│  └─ 视觉时长是否比声明时长更长?
│     └─ 模拟器(60Hz)与设备帧率(120Hz)。为真实硬件重新计算。
│
├─ 弹簧物理效果在设备上异常?
│  ├─ 值是否为特定设备硬编码?
│  │  └─ 使用设备性能类,而非型号
│  ├─ 是否交换了 damping/stiffness 值与 mass/stiffness?
│  │  └─ 检查 CASpringAnimation 参数含义
│  └─ 在模拟器上正常但在设备上异常?
│     └─ 模拟器使用 60Hz。设备可能使用 120Hz。重新计算。
│
└─ 手势 + 动画卡顿?
   ├─ 动画是否在竞争(相同的 keyPath)?
   │  └─ 在添加新动画之前移除旧的动画
   ├─ 手势是否在动画运行时更新图层?
   │  └─ 使用 CADisplayLink 进行同步更新
   └─ 手势是否阻塞了主线程?
      └─ 使用 Instruments > Core Animation 进行分析

常见模式

模式选择规则(强制)

一次仅应用一个模式,按此顺序进行

  1. 始终从模式 1 开始(完成处理程序基础)

    • 如果完成处理程序从未触发 → 模式 1
    • 使用 print 语句(第 33 行)验证完成处理程序在 add() 之前设置
    • 仅当完成处理程序触发但时序错误时,才继续使用模式 2
  2. 然后是模式 2(CATransaction 时长不匹配)

    • 仅当完成处理程序触发但经过时长 != 声明时长时
    • 检查强制优先步骤(第 40-47 行)中的日志
  3. 然后是模式 3(isRemovedOnCompletion)

    • 仅当动画完成但视觉状态恢复时
  4. 模式 4-7 根据具体症状应用(参见第 91+ 行的决策树)

禁止

  • ❌ 同时应用多个模式(“让我同时尝试模式 2 和模式 4”)
  • ❌ 跳过模式 1,因为“我已经知道不是那个问题”
  • ❌ 在不理解为什么需要每个模式的情况下组合它们
  • ❌ 随机尝试模式并希望其中一种能奏效

模式 1:完成处理程序基础

❌ 错误(在添加动画后设置处理程序)

layer.add(animation, forKey: "myAnimation")
animation.completion = { finished in  // ❌ 太晚了!
    print("完成")
}

✅ 正确(在添加动画前设置处理程序)

animation.completion = { [weak self] finished in
    print("🔥 动画完成:finished=\(finished)")
    guard let self = self else { return }
    self.doNextStep()
}
layer.add(animation, forKey: "myAnimation")

原因:完成处理程序必须在动画添加到图层之前设置。设置晚了不会生效。


模式 2:CATransaction 与 animation.duration

❌ 错误(CATransaction 覆盖动画时长)

CATransaction.begin()
CATransaction.setAnimationDuration(2.0)  // ❌ 覆盖所有动画!
let anim = CABasicAnimation(keyPath: "position")
anim.duration = 0.5  // 这会被忽略
layer.add(anim, forKey: nil)
CATransaction.commit()  // 动画耗时 2.0 秒,而非 0.5

✅ 正确(在动画上设置时长,而非事务)

let anim = CABasicAnimation(keyPath: "position")
anim.duration = 0.5
layer.add(anim, forKey: nil)
// 没有 CATransaction 包装

原因:CATransaction.setAnimationDuration() 会影响事务块中所有动画。仅当你想统一更改所有动画时才使用它。


模式 3:isRemovedOnCompletion 与 fillMode

❌ 错误(动画完成后消失)

let anim = CABasicAnimation(keyPath: "opacity")
anim.fromValue = 1.0
anim.toValue = 0.0
anim.duration = 0.5
layer.add(anim, forKey: nil)
// 0.5 秒后,动画被移除并且图层恢复到原始状态

✅ 正确(保留动画状态)

anim.isRemovedOnCompletion = false
anim.fillMode = .forwards  // 动画后保持最终状态
layer.add(anim, forKey: nil)
// 0.5 秒后,动画状态被保留

原因:默认情况下,动画会被移除并且图层会恢复。对于永久状态更改,设置 isRemovedOnCompletion = false 和 fillMode = .forwards。


模式 4:完成处理程序中的弱引用(强制)

❌ 禁止(强引用创建循环引用)

anim.completion = { finished in
    self.property = "value"  // ❌ 确定会产生循环引用
}

✅ 强制(始终使用弱引用)

anim.completion = { [weak self] finished in
    guard let self = self else { return }
    self.property = "value"  // 安全访问
}

为什么这是强制性的,而非可选的

  • CAAnimation 保持完成处理程序存活,直到动画完成
  • 完成处理程序强引用 self(除非显式使用弱引用)
  • 创建循环引用:self → animation → completion → self
  • 即使动画是短命的(0.3 秒并不能阻止它),也会发生内存泄漏

禁止的合理化解释

  • ❌ “动画很短,所以没有循环引用风险”
  • ❌ “我会手动移除动画,所以没问题”
  • ❌ “这段代码路径只运行一次”

在完成处理程序中始终使用 [weak self]。没有例外。


模式 5:多个动画(相同的 keyPath)

❌ 错误(动画冲突)

// 添加动画 1
let anim1 = CABasicAnimation(keyPath: "position.x")
anim1.toValue = 100
layer.add(anim1, forKey: "slide")

// 稍后,添加动画 2
let anim2 = CABasicAnimation(keyPath: "position.x")
anim2.toValue = 200
layer.add(anim2, forKey: "slide")  // ❌ 相同的 key,替换了 anim1!

✅ 正确(在添加前移除)

layer.removeAnimation(forKey: "slide")  // 先移除旧的

let anim2 = CABasicAnimation(keyPath: "position.x")
anim2.toValue = 200
layer.add(anim2, forKey: "slide")

或者使用唯一的 key:

let anim1 = CABasicAnimation(keyPath: "position.x")
layer.add(anim1, forKey: "slide_1")

let anim2 = CABasicAnimation(keyPath: "position.x")
layer.add(anim2, forKey: "slide_2")  // 不同的 key

原因:使用相同的 key 添加动画会替换之前的动画。要么移除旧的动画,要么使用唯一的 key。


模式 6:用于手势与动画同步的 CADisplayLink

❌ 错误(手势直接更新,动画以不同速率更新)

func handlePan(_ gesture: UIPanGestureRecognizer) {
    let translation = gesture.translation(in: view)
    view.layer.position.x = translation.x  // ❌ 同步问题
}

// 分开:
let anim = CABasicAnimation(keyPath: "position.x")
view.layer.add(anim, forKey: nil)  // 因不同步导致卡顿

✅ 正确(使用 CADisplayLink 进行同步)

var displayLink: CADisplayLink?

func startSyncedAnimation() {
    displayLink = CADisplayLink(
        target: self,
        selector: #selector(updateAnimation)
    )
    displayLink?.add(to: .main, forMode: .common)
}

@objc func updateAnimation() {
    // 在同一帧中同时更新手势和动画
    let gesture = currentGesture
    let position = calculatePosition(from: gesture)
    layer.position = position  // 同步更新
}

原因:手势识别器和 CAAnimation 可能以不同的帧率运行。CADisplayLink 将两者同步到屏幕刷新率。


模式 7:弹簧动画设备差异

❌ 错误(为特定设备硬编码)

let springAnim = CASpringAnimation()
springAnim.damping = 0.7  // 为 iPhone 15 Pro 硬编码
springAnim.stiffness = 100
layer.add(springAnim, forKey: nil)  // 在 iPhone 12 上卡顿

✅ 正确(适应设备性能)

let springAnim = CASpringAnimation()

// 使用设备性能类,而非型号
if ProcessInfo.processInfo.processorCount >= 6 {
    // 现代 A 系列(A14+)
    springAnim.damping = 0.7
    springAnim.stiffness = 100
} else {
    // 较旧的 A 系列
    springAnim.damping = 0.85
    springAnim.stiffness = 80
}

layer.add(springAnim, forKey: nil)

原因:弹簧物理效果在 60Hz 和 120Hz 下感觉不同。使用设备类(核心数、GPU)而非型号。


快速参考表

问题检查点修复方法
完成处理程序从不触发处理程序是否在 add() 之前设置将 completion = 移到 add() 之前
时长不匹配是否有 CATransaction 包装?移除外部的 CATransaction 或将动画从中移除
旧设备卡顿值是否为硬编码?使用 ProcessInfo 获取设备类
动画消失isRemovedOnCompletion?设为 false,使用 fillMode = .forwards
手势+动画卡顿更新是否同步?使用 CADisplayLink
多个动画冲突使用相同的 key?使用唯一的 key 或先调用 removeAnimation()
处理程序中的弱引用完成处理程序是否正确捕获?在完成处理程序中始终使用 [weak self]

当你在 30 分钟后仍然卡住时

如果你花了超过 30 分钟,动画仍然有问题:

停止。你可能是:

  1. 跳过了强制步骤(最常见)
  2. 误解了诊断输出
  3. 为你的症状应用了错误的模式
  4. 处于需要 Instruments 分析的 5% 边缘情况

在声称“技能无效”之前,必须完成的检查清单

  • 我运行了强制优先步骤中的所有 4 个诊断块(第 28-63 行)
  • 我粘贴了诊断的准确输出(日志、print 语句)
  • 我从“这告诉你什么”(第 66-72 行)中确定了一个根本原因
  • 我从决策树(第 91+ 行)中应用了第一个匹配的模式
  • 我在真实设备(不仅仅是模拟器)上测试了该模式
  • 我使用 print 语句/日志验证了修复已生效

如果所有复选框都已勾选但仍然有问题

  • 你必须使用 Instruments > Core Animation 进行分析
  • 时间成本:30-60 分钟(对于边缘情况不可避免)
  • 硬编码、asyncAfter 或“发货并抱希望”是被禁止的
  • 在添加任何临时解决方案之前,请寻求指导

时间成本透明

  • 模式 1:2-5 分钟 ...

[出于翻译目的截断]

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

相关技能