К основному содержанию
скилл CX Codex

swiftui-animation · jamesrochabrun — скилл для Claude Code: что делает и как установить

Скилл помогает настраивать пружинные анимации SwiftUI и эффекты Metal-шейдеров в приложениях для iOS и macOS.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add jamesrochabrun/skills --skill swiftui-animation -a claude-code
Открыть на GitHub

Что делает swiftui-animation

Скилл передаёт агенту правила motion-дизайна из гайдлайнов Apple и синтаксис пружин. Он помогает настроить явные вызовы withAnimation, собрать пошаговые цепочки через PhaseAnimator или анимировать экраны с помощью matchedGeometryEffect.

Внутри собраны инструкции по шейдерам Metal для iOS 17+. Ассистент учится применять модификаторы distortionEffect и colorEffect через библиотеку ShaderLibrary, а также встраивать MTKView через UIViewRepresentable, когда штатных модификаторов недостаточно.

Анимации советуют удерживать в пределах 400ms, начиная подбор параметров со значений response: 0.35 и dampingFraction: 0.8. Проверять тайминги придётся на реальном устройстве. Симулятор часто искажает плавность отрисовки кадров.

Какие задачи решает

  • связать элементы двух экранов через matchedGeometryEffect
  • настроить физику пружины с параметрами response и dampingFraction
  • подключить шейдеры Metal через colorEffect или distortionEffect
  • выстроить многофазную анимацию с помощью PhaseAnimator

Примеры запросов агенту

  • Сделай карточку с плавным разворачиванием по тапу на пружине со сглаживанием
  • Настрой hero-анимацию перехода с миниатюры на детальный экран через matchedGeometryEffect
  • Добавь distortionEffect для искажения слоя волной через ShaderLibrary

Как установить swiftui-animation

1Через Skills CLI (Vercel)

npx skills add jamesrochabrun/skills --skill swiftui-animation -a claude-code

2Вручную: положить файлы

~/.claude/skills/swiftui-animation/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/swiftui-animation/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о swiftui-animation

Как установить swiftui-animation в Claude Code?

Выполните команду npx skills add jamesrochabrun/skills --skill swiftui-animation -a claude-code.

Что делает скилл swiftui-animation?

Он обучает агента строить пружинные анимации, переходы между экранами, сложные таймлайны и шейдерные эффекты Metal для приложений на SwiftUI.

Почему анимация matchedGeometryEffect может дёргаться при переходе?

Оба представления должны использовать одинаковый идентификатор и общий @Namespace, состояние нужно менять внутри withAnimation, а порядок наложения слоёв регулировать через zIndex.

Исходный текст

SKILL.md · MIT
---
name: swiftui-animation
description: This skill provides comprehensive guidance for implementing advanced SwiftUI animations, transitions, matched geometry effects, and Metal shader integration. Use when building animations, view transitions, hero animations, or GPU-accelerated effects in SwiftUI apps for iOS and macOS.
---

# SwiftUI Animation Expert

Expert guidance for implementing advanced SwiftUI animations and Metal shader integration. Covers animation curves, springs, transitions, matched geometry effects, PhaseAnimator, KeyframeAnimator, and GPU-accelerated shader effects.

## When to Use This Skill

- Understanding motion design principles and when to use animation
- Making animations accessible and platform-appropriate
- Implementing animations in SwiftUI (springs, easing, keyframes)
- Creating view transitions (fade, slide, scale, custom)
- Building hero animations with matchedGeometryEffect
- Adding GPU-accelerated effects with Metal shaders
- Optimizing animation performance
- Creating multi-phase orchestrated animations

## Quick Reference

### Animation Basics

```swift
// Explicit animation (preferred)
withAnimation(.spring(response: 0.4, dampingFraction: 0.75)) {
    isExpanded.toggle()
}

// iOS 17+ spring presets
withAnimation(.snappy) { ... }  // Fast, small bounce
withAnimation(.smooth) { ... }  // Gentle, no bounce
withAnimation(.bouncy) { ... }  // More bounce
```

### Common Transitions

```swift
// Basic
.transition(.opacity)
.transition(.scale)
.transition(.slide)
.transition(.move(edge: .bottom))

// Combined
.transition(.move(edge: .trailing).combined(with: .opacity))

// Asymmetric
.transition(.asymmetric(
    insertion: .move(edge: .bottom),
    removal: .opacity
))
```

### Matched Geometry Effect

```swift
@Namespace var namespace

// Source view
ThumbnailView()
    .matchedGeometryEffect(id: "hero", in: namespace)

// Destination view
DetailView()
    .matchedGeometryEffect(id: "hero", in: namespace)
```

### Metal Shader Effects (iOS 17+)

```swift
// Color manipulation
.colorEffect(ShaderLibrary.invert())

// Pixel displacement
.distortionEffect(
    ShaderLibrary.wave(.float(time)),
    maxSampleOffset: CGSize(width: 20, height: 20)
)

// Full layer access
.layerEffect(ShaderLibrary.blur(.float(radius)), maxSampleOffset: .zero)
```

## Reference Materials

Detailed documentation is available in `references/`:

- **motion-guidelines.md** - HIG Motion design principles
  - Purpose-driven motion philosophy
  - Accessibility requirements
  - Platform-specific considerations (iOS, visionOS, watchOS)
  - Animation anti-patterns to avoid

- **animations.md** - Complete animation API guide
  - Implicit vs explicit animations
  - Spring parameters and presets
  - Animation modifiers (speed, delay, repeat)
  - PhaseAnimator for multi-step sequences
  - KeyframeAnimator for property-specific timelines
  - Custom animatable properties

- **transitions.md** - View transition guide
  - Built-in transitions (opacity, scale, slide, move)
  - Combined and asymmetric transitions
  - Matched geometry effect implementation
  - Hero animation patterns
  - Content transitions (iOS 17+)
  - Custom transition creation

- **metal-shaders.md** - GPU shader integration
  - SwiftUI shader modifiers (colorEffect, distortionEffect, layerEffect)
  - Writing Metal shader functions
  - Embedding MTKView with UIViewRepresentable
  - Cross-platform Metal integration (iOS/macOS)
  - Performance considerations

## Common Patterns

### Expandable Card

```swift
struct ExpandableCard: View {
    @State private var isExpanded = false

    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: isExpanded ? 20 : 12)
                .fill(.blue)
                .frame(
                    width: isExpanded ? 300 : 150,
                    height: isExpanded ? 400 : 100
                )
        }
        .onTapGesture {
            withAnimation(.spring(response: 0.35, dampingFraction: 0.75)) {
                isExpanded.toggle()
            }
        }
    }
}
```

### List Item Appearance

```swift
ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
    ItemRow(item: item)
        .transition(.asymmetric(
            insertion: .move(edge: .trailing).combined(with: .opacity),
            removal: .move(edge: .leading).combined(with: .opacity)
        ))
        .animation(.spring().delay(Double(index) * 0.05), value: items)
}
```

### Pulsing Indicator

```swift
Circle()
    .fill(.blue)
    .frame(width: 20, height: 20)
    .scaleEffect(isPulsing ? 1.2 : 1.0)
    .opacity(isPulsing ? 0.6 : 1.0)
    .onAppear {
        withAnimation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true)) {
            isPulsing = true
        }
    }
```

## Best Practices

1. **Motion should be purposeful** - Don't add animation for its own sake; support the experience without overshadowing it
2. **Make motion optional** - Supplement with haptics and audio; never use motion as the only way to communicate
3. **Aim for brevity** - Brief, precise animations feel lightweight and convey information effectively
4. **Prefer explicit animations** - Use `withAnimation` over `.animation()` modifier for clarity
5. **Use spring animations** - They feel more natural and iOS-native
6. **Start with `.spring(response: 0.35, dampingFraction: 0.8)`** - Good default for most interactions
7. **Keep animations under 400ms** - Longer feels sluggish
8. **Let people cancel motion** - Don't force users to wait for animations to complete
9. **Test on device** - Simulator animation timing differs
10. **Profile shader performance** - GPU time matters for complex effects

## Troubleshooting

### Animation not working

- Ensure state change is wrapped in `withAnimation`
- Check that the property is animatable
- Verify the view is actually changing

### Matched geometry jumps

- Both views must use the same ID and namespace
- Use explicit `withAnimation` when toggling
- Check `zIndex` for proper layering

### Shader not appearing

- Verify `.metal` file is added to target
- Check shader function signature matches expected format
- Ensure `maxSampleOffset` is set correctly for distortion effects

© jamesrochabrun · MIT · jamesrochabrun/skills

Похожие скиллы

Всё по теме «Мобильная разработка» →

Сначала — swiftui-animation от других авторов.

swiftui-animation dpearson2699 Скилл помогает настраивать анимации в SwiftUI. Он подсказывает подходящие API для пружин, фазовых переходов и соблюдения правил доступности. CX Codex +1 5 400установок swiftui-design-skill wholiver Помогает проектировать экраны SwiftUI для iOS и macOS без шаблонного визуала. Пригодится при вёрстке прототипов и подборе дизайн-направления с нуля. CX Codex +1 1 000установок swiftui-patterns affaan-m Задаёт правила современной разработки на SwiftUI: переход на @Observable, типобезопасная навигация и оптимизация рендеринга. Пригодится при верстке экранов под iOS и macOS. CX Codex +1 4 600установок swiftui-whats-new-27 superagents-lab Справочник по изменениям SwiftUI в SDK 27 для агентов кодинга. Помогает адаптировать проект под новые API и исправить сборку после перехода @State на макросы. CX Codex +1 737установок design rshankras Набор дизайн-скиллов для интерфейсов Apple: Liquid Glass, анимации, игровой отклик, UX-тексты, SF Symbols и типографика. Пригодится, когда экран выглядит плоско и нужен план правок. CX Codex +1 677установок swiftui-motion AThevon Задаёт правила и готовые паттерны анимаций SwiftUI для ИИ-агента. Помогает настроить пружины, переходы и многофазные эффекты без лишнего визуального мусора. CX Codex +1 943установок guide-swiftui-animations Prisma-Labs-Dev Скилл-руководство по анимациям SwiftUI: неявные и явные анимации, переходы, фазовые и keyframe-анимации, протокол Animatable. CX Codex +1 347установок

Из того же набора8

prd-generator Скилл ведёт агента через вопросы о задаче, пользователях и метриках, а потом собирает из ответов готовый PRD по шаблону. CX Codex +1 1 200установок trading-plan-generator Скилл формирует торговые планы с правилами управления риском, точками входа и выхода, а также расчётом позиций. Пригодится трейдерам на акциях, опционах или крипте. CX Codex +1 1 100установок apple-hig-designer Скилл помогает создавать интерфейсы iOS для iPhone, iPad и Apple Watch по стандартам Apple HIG. Он генерирует компоненты SwiftUI и следит за доступностью. CX Codex +1 1 000установок math-teacher Скилл превращает объяснение математики в интерактивные HTML-страницы с графиками, бегунками и игровыми очками. Пригодится для наглядного разбора тем от дробей до интегралов. CX Codex +1 871установок leetcode-teacher Скилл разворачивает интерактивные песочницы с практическими задачами из реальных сервисов вроде Uber и Slack. Помогает разбирать 20 алгоритмических паттернов на четырёх языках. CX Codex +1 592установок book-illustrator Помогает создавать иллюстрации для детских книг с учётом возраста от 0 до 12 лет, теории цвета и правил композиции. Пригодится при оформлении обложек, разворотов и персонажей. CX Codex +1 453установок frontend-designer Скилл для сборки доступных и адаптивных компонентов интерфейса: дизайн-токены, современный CSS, паттерны React, Vue и Svelte. CX Codex +1 335установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой