はじめに
iOS17からCustomAnimation
というものが追加されました。
これは名前の通り、アニメーションをカスタムできる機能っぽいです。
使ってみたので記事にしておきます。
サンプルアプリ
実装
経過時間の小数点第一の偶数と奇数を判定して進行値に前後する値を渡す事で、点滅させる事ができます。
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)