1
1

【SwiftUI】CustomAnimationを使って点滅アニメーションを自作する(iOS17)

Posted at

はじめに

iOS17からCustomAnimationというものが追加されました。
これは名前の通り、アニメーションをカスタムできる機能っぽいです。
使ってみたので記事にしておきます。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-11-26 at 23.03.52.gif

実装

経過時間の小数点第一の偶数と奇数を判定して進行値に前後する値を渡す事で、点滅させる事ができます。

import SwiftUI

struct ContentView: View {
    @State private var isHidden = false
    
    var body: some View {
        VStack(spacing: 10) {
            if isHidden {
                Circle().padding(20)
            }
            
            Button {
                isHidden.toggle()
            } label: {
                Text("アニメーション")
            }
        }
        .animation(.init(BlinkAnimation()), value: isHidden)
    }
}

struct BlinkAnimation: CustomAnimation {
    func animate<V>(value: V, time: TimeInterval, context: inout AnimationContext<V>) -> V? where V : VectorArithmetic {
        guard time <= 1 else { return nil }
        return value.scaled(by: timeBasedScale(time))
    }

    func timeBasedScale(_ time: TimeInterval) -> CGFloat {
        let assss = Int(time * 10)
        if assss % 2 == 0 {
            return time * 2
        } else {
            return time / 2
        }
    }
}

おわり

以下のようにする事で使用側では簡潔に指定する事ができます。

extension CustomAnimation where Self == BlinkAnimation {
    static var blink: BlinkAnimation {
        .init()
    }
}
 .animation(.init(.blink), value: isHidden)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1