Communitygithub.com

ComeOnOliver/skillshub

當 CAAnimation 完成處理器未觸發、彈簧物理效果在裝置上顯示異常、動畫持續時間與實際時間不符、手勢與動畫互動導致卡頓,或模擬器與真實硬體之間計時不一致時,可進行系統化的 CAAnimation 診斷,包含 CATransaction 模式、幀率感知與裝置特定行為處理。

skillshub 是什麼?

這項技能旨在系統性地診斷並修復 UIKit 中 CAAnimation 的常見問題。許多開發者遇到動畫完成處理器未觸發、動畫時長與視覺感受不符、彈簧物理效果在特定裝置上表現異常,或手勢與動畫互動導致卡頓等問題時,常誤判為裝置錯誤,但實際上根源通常是 CATransaction 時序問題、圖層狀態設錯或對幀率的假設錯誤。此技能提供強制性的初步診斷步驟,協助找出真正的根本原因,並附有決策樹引導使用者依序套用七種常見的解決模式,例如設定完成處理器、處理 CATransaction 覆蓋問題、修正 `isRemovedOnCompletion` 的保留行為、強制使用 `[weak self]` 避免記憶體洩漏,以及透過 `CADisplayLink` 同步手勢與動畫更新。此外,也特別強調必須在真實裝置上測試,並根據裝置效能等級動態調整動畫參數,而非針對單一型號硬編碼。

相容平台~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 本身的錯誤。

危險訊號 — 懷疑 CAAnimation 問題

若你發現任何以下情況,應懷疑是動畫邏輯而非裝置行為問題:

  • 完成處理器在模擬器上觸發,但在裝置上未觸發
  • 動畫持續時間 (0.5 秒) 與視覺持續時間 (1.2 秒) 不符
  • 彈簧動畫在 iPhone 15 Pro 上正常,但在較舊裝置上卡頓
  • 手勢與動畫一同使用時會卡頓(分別使用時正常)
  • 在完成處理器中使用 [weak self],但不確定原因
  • ❌ 禁止 硬編碼持續時間/數值來「匹配實際發生的情況」
    • 這會將裝置特定問題帶給使用不同硬體的使用者
    • 不得將其合理化為「暫時修復」或「夠好了」

關鍵區別:模擬器通常會隱藏時序問題(僅 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("圖層 timeOffset: \(layer.timeOffset)")  // != 0 代表動畫有偏移

這告訴你什麼

  • 顯示「完成已觸發」 → 處理器有觸發,問題在回呼程式碼
  • 未顯示「完成已觸發」 → 處理器未觸發,檢查 CATransaction/圖層狀態
  • 已耗時間 == 宣告值 → 持續時間正確,視覺卡頓來自畫面
  • 已耗時間 != 宣告值 → CATransaction 包裹更改了持續時間
  • 圖層速度 != 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 包裹
│  │  └─ 檢查:動畫期間 App 是否進入背景
│  └─ 在模擬器和裝置上都發生?
│     ├─ 檢查:完成處理器是否在新增動畫「之前」設定
│     └─ 檢查:[weak self] 是否確實被捕捉(在完成前不是 nil)
│
├─ 持續時間不符(宣告值 != 視覺值)?
│  ├─ 圖層速度 != 1.0?
│  │  └─ 有東西縮放了動畫持續時間。找出並修正。
│  ├─ 動畫是否被包裹在 CATransaction 中?
│  │  └─ CATransaction.setAnimationDuration() 會覆蓋動畫的持續時間
│  └─ 視覺持續時間比宣告值「更長」?
│     └─ 模擬器 (60Hz) 對比裝置幀率 (120Hz)。為真實硬體重新計算。
│
├─ 彈簧物理效果在裝置上異常?
│  ├─ 是否針對單一裝置硬編碼了數值?
│  │  └─ 使用裝置效能等級,而非型號
│  ├─ 阻尼/剛度數值是否與質量/剛度互換?
│  │  └─ 檢查 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)")
    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:完成處理器中的 Weak Self(強制)

❌ 禁止(強 self 會導致保留循環)

anim.completion = { finished in
    self.property = "value"  // ❌ 必定造成保留循環
}

✅ 強制(一律使用 weak self)

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

為何這是「強制」,而非選擇性

  • CAAnimation 會讓完成處理器保持存活,直到動畫完成
  • 完成處理器會強烈捕捉 self(除非明確使用 weak)
  • 造成保留循環:self → 動畫 → 完成處理器 → 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完成處理器是否正確捕捉?在完成處理器中「一律」使用 [weak self]

當你卡住超過 30 分鐘

如果你已經花費超過 30 分鐘,但動畫仍無法修復:

停止。你要嘛

  1. 跳過了某個強制性步驟(最常見)
  2. 錯誤解讀了診斷輸出
  3. 針對你的症狀套用了錯誤的模式
  4. 屬於那 5% 需要 Instruments 分析的邊緣案例

在聲稱「技能沒用」之前的強制性檢查清單

  • 我已經執行了強制性第一步驟中的所有 4 個診斷區塊(第 28-63 行)
  • 我貼出了診斷的「確切」輸出(日誌、print 陳述式)
  • 我從「這告訴你什麼」中找出了一個根本原因(第 66-72 行)
  • 我套用了決策樹中第一個符合的模式(第 91 行起)
  • 我在「實體裝置」上測試了該模式,而不僅僅是模擬器
  • 我使用 print 陳述式/日誌驗證了該修復是否有效

如果所有項目都已勾選但仍然無法修復

  • 你「必須」使用 Instruments > Core Animation 進行分析
  • 時間成本:30-60 分鐘(邊緣案例無法避免)
  • 禁止使用硬編碼、asyncAfter 或「上線賭運氣」
  • 在加入任何解決方案之前,請先尋求指導

時間成本透明化

  • 模式 1: 2-5 分鐘
  • 模式 2: 5-10 分鐘
  • 模式 3: 5-10 分鐘
  • 模式 4: 2-5 分鐘
  • 模式 5: 5-10 分鐘
  • 模式 6: 15-30 分鐘
  • 模式 7: 10-20 分鐘
  • Instruments 分析: 30-60 分鐘

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

相關技能