LoginSignup
0
2

More than 1 year has passed since last update.

【SwiftUI】特定の条件でのみアニメーションをループさせる

Posted at

はじめに

特定条件の場合のみ、ループアニメーションを付与します。

サンプルアプリ

Simulator Screen Recording - iPhone 14 Pro - 2023-02-04 at 20.16.09.gif

やりかた

ContentView
import SwiftUI

struct ContentView: View {
    @State var isAnimation: Bool = false
    var body: some View {
        VStack(spacing: 50) {
            Toggle("", isOn: $isAnimation)
                .labelsHidden()

            Button {
                print()
            } label: {
                Text("ボタン")
            }
            .buttonStyle(.borderedProminent)
            .scaleEffect(isAnimation ? 1.5 : 1.0)
            .animation(.default.repeat(while: isAnimation), value: isAnimation)
        }
    }
}
Animation+
import struct SwiftUI.Animation

extension Animation {
    func `repeat`(while expression: Bool, autoreverses: Bool = true) -> Animation {
        if expression {
            return self.repeatForever(autoreverses: autoreverses)
        } else {
            return self
        }
    }
}

おわり

animationのAPIが新しくなってからはじめに使いました笑

0
2
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
0
2