2
2

More than 3 years have passed since last update.

SwiftUIでカラーをアニメーションする方法

Posted at

概要

SwiftUIで画面表示後にカラーが変化するようにしたかったので、その方法を記載します。
【デモ】
colorAnimationDemo.gif

方法

@Stateでcolorを監視できるようにします。
画面の表示時にonAppearが呼ばれるので、
withAnimationを用いて、colorプロパティを指定した秒数をかけて変化させます。

import SwiftUI

struct ContentView: View {

    @State private var color: Color = .blue

    var body: some View {
        Rectangle()
            .onAppear(perform: {
                // 画面が表示されたら3秒かけて赤色に変化させる
                withAnimation(.easeInOut(duration: 3), {
                    color = .red
                })
            })
            .foregroundColor(color)
            .ignoresSafeArea()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ボタンを押したらアニメーションで色を変化させたいとかであれば、onChangeで検知すればできそうですね!

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