[SwiftUI]アニメーションを移動に追加するには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

ビューの移動にアニメーションを付与する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

アニメーションを移動に付与するには、animation修飾子もしくはwithAnimationを使います。

まず、移動するビューにoffset修飾子を付与し、offsetの引数「x」と引数「y」にビューの位置を指定します。

この時、引数「x」と引数「y」の位置を、変数で変化するようにします。

//offset修飾子で位置を指定。位置は変数を使い、変化するようにする。
View()
    .offset(x: positionX, y: positionY)

そして、animation修飾子やwithAnimationで、位置の変数の変化に合わせてアニメーションをするようにします。

~~~~animation修飾子~~~~
View()
    .offset(・・・)
    .animation(.default, value: position)

~~~withAnimation~~~
withAnimation(.default) {
    //位置の変数の変更
}

animation修飾子の場合は、変数を引数に「value」に指定することで、変数の変化に合わせてアニメーションをするようになります。

withAnimationの場合は、変数をwithAnimationのクロージャー内で変更することで、アニメーションをするようになります。

使用例

struct ContentView: View {
    @State var isRight = false
    @State var positionX : CGFloat = -100
    
    var body: some View {
        VStack {
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: 100, height: 100)
                .offset(x: isRight ? 100 : -100, y: 0)
            Button("Move Blue") {
                withAnimation(.spring(response: 0.3, dampingFraction: 0.3, blendDuration: 0)) {
                    self.isRight.toggle()
                }
            }
            .padding()
            .buttonStyle(.bordered)
            
            Rectangle()
                .foregroundColor(.yellow)
                .frame(width: 100, height: 100)
                .offset(x: positionX, y: 0)
                .animation(.easeInOut(duration: 1), value: positionX)
            Button("Move Yellow") {
                if positionX == 100 {
                    positionX = -100
                } else {
                    positionX += 100
                }
            }
            .padding()
            .buttonStyle(.bordered)
        }
    }
}

コメント

タイトルとURLをコピーしました