SwiftUI アニメーションとトランジション は何をしますか?
SwiftUIアニメーション、新しい@Animatableマクロ(iOS 26)、トランジション、モーションデザインのベストプラクティスを網羅した、モダンなiOS開発のための包括的なガイドです。
前提条件
- PhaseAnimator/KeyframeAnimatorを使用するにはiOS 17+
- @Animatableマクロを使用するにはiOS 26+
- Xcode 26+
@Animatable マクロ (iOS 26 - 新機能!)
カスタムアニメーションの革命
iOS 26で導入された@Animatableマクロは、カスタムシェイプやビューのアニメーションにこれまで必要だった面倒なボイラープレートを排除します。
iOS 26以前(手動での対応)
// 旧来の方法 - 大量のボイラープレート
struct PieSlice: Shape {
var startAngle: Angle
var endAngle: Angle
// 手動によるanimatableDataの実装が必要
var animatableData: AnimatablePair<Double, Double> {
get {
AnimatablePair(startAngle.radians, endAngle.radians)
}
set {
startAngle = Angle(radians: newValue.first)
endAngle = Angle(radians: newValue.second)
}
}
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius = min(rect.width, rect.height) / 2
path.move(to: center)
path.addArc(center: center, radius: radius,
startAngle: startAngle, endAngle: endAngle,
clockwise: false)
path.closeSubpath()
return path
}
}
iOS 26以降(@Animatableを使用)
// 新しい方法 - @Animatableを付けるだけ
@Animatable
struct PieSlice: Shape {
var startAngle: Angle
var endAngle: Angle
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius = min(rect.width, rect.height) / 2
path.move(to: center)
path.addArc(center: center, radius: radius,
startAngle: startAngle, endAngle: endAngle,
clockwise: false)
path.closeSubpath()
return path
}
}
@AnimatableIgnored
アニメーションからプロパティを除外する:
@Animatable
struct CustomShape: Shape {
var animatedValue: CGFloat
@AnimatableIgnored var staticConfiguration: Bool // アニメーション対象外
func path(in rect: CGRect) -> Path {
// 両方の値を使用するが、animatedValueのみがアニメーションする
}
}
アニメーションでサポートされる型
@Animatableマクロは以下を自動的に処理します:
CGFloat,Double,FloatAngleCGSize,CGPoint,CGRectUnitPointColor(コンポーネント補間)VectorArithmeticに準拠したカスタム型
複数プロパティの複雑な例
@Animatable
struct MorphingShape: Shape {
var cornerRadius: CGFloat
var insetAmount: CGFloat
var rotation: Angle
@AnimatableIgnored var fillColor: Color
func path(in rect: CGRect) -> Path {
let insetRect = rect.insetBy(dx: insetAmount, dy: insetAmount)
var path = Path(roundedRect: insetRect, cornerRadius: cornerRadius)
let transform = CGAffineTransform(rotationAngle: rotation.radians)
return path.applying(transform)
}
}
// 使用例
struct MorphingView: View {
@State private var isExpanded = false
var body: some View {
MorphingShape(
cornerRadius: isExpanded ? 50 : 10,
insetAmount: isExpanded ? 20 : 50,
rotation: isExpanded ? .degrees(45) : .zero,
fillColor: .blue
)
.fill(.blue)
.frame(width: 200, height: 200)
.onTapGesture {
withAnimation(.spring(duration: 0.6, bounce: 0.3)) {
isExpanded.toggle()
}
}
}
}
withAnimation
基本的な使い方
struct ContentView: View {
@State private var isExpanded = false
var body: some View {
VStack {
Rectangle()
.frame(width: isExpanded ? 200 : 100,
height: isExpanded ? 200 : 100)
Button("Toggle") {
withAnimation {
isExpanded.toggle()
}
}
}
}
}
アニメーションタイプを指定
withAnimation(.spring(duration: 0.5, bounce: 0.3)) {
isExpanded.toggle()
}
withAnimation(.easeInOut(duration: 0.3)) {
opacity = 1.0
}
withAnimation(.linear(duration: 1.0)) {
progress = 1.0
}
完了ハンドラ(iOS 17+)
withAnimation(.easeInOut(duration: 0.5)) {
showDetails = true
} completion: {
// アニメーション完了時に呼ばれる
print("Animation finished")
fetchMoreData()
}
異なるタイミングでのネストアニメーション
Button("Animate") {
withAnimation(.spring(duration: 0.4)) {
isExpanded = true
}
withAnimation(.easeOut(duration: 0.6).delay(0.2)) {
opacity = 1.0
}
}
アニメーションタイプ
組み込みアニメーション
// Linear - 一定速度
.linear(duration: 0.3)
// Ease系 - 加速/減速
.easeIn(duration: 0.3) // ゆっくり開始
.easeOut(duration: 0.3) // ゆっくり終了
.easeInOut(duration: 0.3) // 両方ゆっくり
// デフォルト(イーズイン/アウト)
.default
スプリングアニメーション(モダン)
// 持続時間とバウンスを指定したモダンスプリング
.spring(duration: 0.5, bounce: 0.3)
// バウンス値:
// 0.0 = バウンスなし(臨界減衰)
// 0.5 = 中程度のバウンス
// 1.0 = 最大バウンス(収束しない)
// オーバーシュート用の追加バウンスパラメータ
.spring(duration: 0.5, bounce: 0.4, blendDuration: 0.2)
スプリングプリセット
// Bouncy - 遊び心があり、エネルギッシュ
.bouncy
.bouncy(duration: 0.4, extraBounce: 0.1)
// Snappy - 素早く、応答性が高い
.snappy
.snappy(duration: 0.3, extraBounce: 0.05)
// Smooth - 穏やかでエレガント
.smooth
.smooth(duration: 0.5, extraBounce: 0.0)
インタラクティブスプリング
// ジェスチャ駆動のアニメーション用
.interactiveSpring()
.interactiveSpring(response: 0.3, dampingFraction: 0.7)
// ドラッグジェスチャに最適
.interactiveSpring(response: 0.15, dampingFraction: 0.86, blendDuration: 0.25)
カスタムタイミングカーブ
// ベジェ曲線によるタイミング
.timingCurve(0.2, 0.8, 0.2, 1.0, duration: 0.5)
// パラメータ: (x1, y1, x2, y2)
// 開始: (0, 0), 終了: (1, 1)
// 制御点が曲線の形状を定義
アニメーションモディファイア
// 開始前の遅延
.spring().delay(0.2)
// 速度倍率
.spring().speed(2.0) // 2倍の速さ
// 繰り返し
.linear(duration: 1.0).repeatCount(3)
.linear(duration: 1.0).repeatForever()
// 自動反転
.easeInOut(duration: 0.5).repeatForever(autoreverses: true)
明示的アニメーションモディファイア
推奨されるアプローチ
struct ContentView: View {
@State private var scale = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
// 明示的: scaleが変化したときのみアニメーション
.animation(.spring, value: scale)
.onTapGesture {
scale = scale == 1.0 ? 1.5 : 1.0
}
}
}
なぜ明示的アニメーションが優れているのか
// 避ける: 暗黙的アニメーション(すべてをアニメーション)
Circle()
.animation(.spring) // 新しいiOSでは非推奨警告
// 推奨: 明示的アニメーション(正確な制御)
Circle()
.animation(.spring, value: specificValue)
複数の明示的アニメーション
struct MultiAnimatedView: View {
@State private var scale = 1.0
@State private var opacity = 1.0
@State private var rotation = 0.0
var body: some View {
Rectangle()
.scaleEffect(scale)
.opacity(opacity)
.rotationEffect(.degrees(rotation))
// プロパティごとに異なるアニメーション
.animation(.bouncy, value: scale)
.animation(.easeOut(duration: 0.2), value: opacity)
.animation(.spring(duration: 1.0), value: rotation)
}
}
トランジション
基本的なトランジション
struct ContentView: View {
@State private var showDetail = false
var body: some View {
VStack {
if showDetail {
DetailView()
.transition(.slide)
}
Button("Toggle") {
withAnimation {
showDetail.toggle()
}
}
}
}
}
組み込みトランジション
.transition(.opacity) // フェードイン/アウト
.transition(.scale) // 中央からスケール
.transition(.scale(scale: 0.5)) // 50%からスケール
.transition(.slide) // 先頭端からスライド
.transition(.move(edge: .top)) // 特定の端から移動
.transition(.push(from: .bottom)) // 置き換えながらプッシュ
.transition(.offset(x: 100, y: 0)) // カスタムオフセット
複合トランジション
// 複数のトランジションを組み合わせる
.transition(.scale.combined(with: .opacity))
// 連鎖結合
.transition(
.scale(scale: 0.8)
.combined(with: .opacity)
.combined(with: .offset(y: 20))
)
非対称トランジション
// 挿入と削除で異なるトランジション
.transition(.asymmetric(
insertion: .scale.combined(with: .opacity),
removal: .slide
))
// 一般的なパターン: 一方からスライドイン、他方からスライドアウト
.transition(.asymmetric(
insertion: .push(from: .trailing),
removal: .push(from: .leading)
))
カスタムトランジション
extension AnyTransition {
static var flipFromBottom: AnyTransition {
.modifier(
active: FlipModifier(angle: -90),
identity: FlipModifier(angle: 0)
)
}
}
struct FlipModifier: ViewModifier {
let angle: Double
func body(content: Content) -> some View {
content
.rotation3DEffect(
.degrees(angle),
axis: (x: 1, y: 0, z: 0)
)
.opacity(angle == 0 ? 1 : 0)
}
}
// 使用例
DetailView()
.transition(.flipFromBottom)
Phase Animator (iOS 17+)
基本的な使い方
enum AnimationPhase: CaseIterable {
case initial
case middle
case final
var scale: CGFloat {
switch self {
case .initial: return 1.0
case .middle: return 1.2
case .final: return 1.0
}
}
var opacity: Double {
switch self {
case .initial: return 1.0
case .middle: return 0.5
case .final: return 1.0
}
}
}
struct PulsingView: View {
var body: some View {
PhaseAnimator(AnimationPhase.allCases) { phase in
Circle()
.fill(.blue)
.scaleEffect(phase.scale)
.opacity(phase.opacity)
}
}
}
トリガーによるアニメーション
struct TriggerableAnimation: View {
@State private var trigger = false
var body: some View {
VStack {
PhaseAnimator(
AnimationPhase.allCases,
trigger: trigger
) { phase in
Star()
.scaleEffect(phase.scale)
.rotationEffect(.degrees(phase.rotation))
}
Button("Animate") {
trigger.toggle()
}
}
}
}
フェーズごとのカスタムアニメーション
PhaseAnimator(AnimationPhase.allCases) { phase in
ContentView(phase: phase)
} animation: { phase in
switch phase {
case .initial: .spring(duration: 0.3)
case .middle: .easeOut(duration: 0.2)
case .final: .bouncy
}
}
Keyframe Animator (iOS 17+)
基本的なキーフレームアニメーション
struct AnimationValues {
var scale = 1.0
var rotation = 0.0
var yOffset = 0.0
}
struct BouncingView: View {
@State private var trigger = false
var body: some View {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.keyframeAnimator(
initialValue: AnimationValues(),
trigger: trigger
) { content, value in
content
.scaleEffect(value.scale)
.rotationEffect(.degrees(value.rotation))
.offset(y: value.yOffset)
} keyframes: { _ in
KeyframeTrack(\score) {
SpringKeyframe(1.2, duration: 0.2)
SpringKeyframe(0.9, duration: 0.15)
SpringKeyframe(1.0, duration: 0.15)
}
KeyframeTrack(\.rotation) {
LinearKeyframe(0, duration: 0.1)
SpringKeyframe(10, duration: 0.15)
SpringKeyframe(-10, duration: 0.15)
SpringKeyframe(0, duration: 0.1)
}
KeyframeTrack(\.yOffset) {
SpringKeyframe(-30, duration: 0.2)
SpringKeyframe(0, duration: 0.3)
}
}
.onTapGesture {
trigger.toggle()
}
}
}
キーフレームの種類
KeyframeTrack(\.value) {
// 線形補間
LinearKeyframe(targetValue, duration: 0.3)
// スプリングベースの補間
SpringKeyframe(targetValue, duration: 0.3)
SpringKeyframe(targetValue, duration: 0.3, spring: .bouncy)
// 3次ベジェ補間
CubicKeyframe(targetValue, duration: 0.3)
// アニメーションなしで移動
MoveKeyframe(targetValue)
}
複雑なマルチトラックアニメーション
struct ComplexAnimationValues {
var xOffset = 0.0
var yOffset = 0.0
var scale = 1.0
var opacity = 1.0
var blur = 0.0
}
struct ComplexAnimation: View {
@State private var animating = false
var body: some View {
Image(systemName: "star.fill")
.font(.system(size: 50))
.keyframeAnimator(
initialValue: ComplexAnimationValues(),
repeating: animating
) { content, value in
content
.offset(x: value.xOffset, y: value.yOffset)
.scaleEffect(value.scale)
.opacity(value.opacity)
.blur(radius: value.blur)
} keyframes: { _ in
KeyframeTrack(\.scale) {
CubicKeyframe(1.5, duration: 0.4)
CubicKeyframe(0.8, duration: 0.2)
CubicKeyframe(1.2, duration: 0.3)
CubicKeyframe(1.0, duration: 0.1)
}
KeyframeTrack(\.opacity) {
LinearKeyframe(1.0, duration: 0.0)
LinearKeyframe(0.3, duration: 0.4)
LinearKeyframe(1.0, duration: 0.6)
}
KeyframeTrack(\.blur) {
LinearKeyframe(0.0, duration: 0.2)
LinearKeyframe(5.0, duration: 0.4)
LinearKeyframe(0.0, duration: 0.4)
}
}
.onTapGesture {
animating.toggle()
}
}
}
インタラクティブモーションデザイン
ジェスチャベースのアニメーション
struct DraggableView: View {
@State private var offset = CGSize.zero
@State private var isDragging = false
var body: some View {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.scaleEffect(isDragging ? 1.2 : 1.0)
.offset(offset)
.gesture(
DragGesture()
.onChanged { value in
offset = value.translation
withAnimation(.snappy) {
isDragging = true
}
}
.onEnded { value in
withAnimation(.spring(duration: 0.5, bounce: 0.3)) {
offset = .zero
isDragging = false
}
}
)
}
}
アニメーション可能な値の永続化
状態の変更時だけでなく、アニメーション中にビューを更新するにはanimatableモディファイアを使用します。
ベストプラクティス
パフォーマンス
// 良い例: 不透明なビュー、アニメーション可能なプロパティのみアニメーション
.animation(.default, value: someProperty)
// 避ける例: 複雑なレイアウト計算のアニメーション
.animation(.default) // 現在のiOSでは非推奨
// 可能であれば `.drawingGroup()` を使用
.animation(.spring, value: opacity)
.drawingGroup()
読みやすさとメンテナンス性
// アニメーションを拡張にカプセル化
extension Animation {
static var smoothSpring: Animation {
.spring(duration: 0.4, bounce: 0.2)
}
static var quickSnap: Animation {
.snappy(duration: 0.2)
}
}
// 使用例
.animation(.smoothSpring, value: scale)
アニメーションのデバッグ
UIView.animateをSwiftUIのビューで使用しないでください。withAnimationコールバック内での状態変更は適切なアニメーションとなることを確認してください。- 関連のない状態変更が意図しない副作用を引き起こさないように、
animation(_:value:)を使用してください。
トラブルシューティング
| 問題 | 解決策 |
|---|---|
| アニメーションが機能しない | withAnimation 内で状態を変更しているか確認 |
| 予期しないアニメーション | 明示的 animation(_:value:) に切り替え |
| カスタムシェイプがアニメーションしない | @Animatable を追加、または animatableData を実装 |
| パフォーマンスの問題 | 不透明なビューを使用、.drawingGroup() を試す、頻繁な変更を避ける |
| トランジションが機能しない | ビューが if または switch ブロック内にあるか確認 |
| フェーズが正しくない | フェーズが CaseIterable に準拠しているか確認 |
| キーフレームがスキップされる | トラック時間が合計アニメーション時間と一致しているか確認 |