4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Qiita全国学生対抗戦Advent Calendar 2023

Day 22

【SwiftUI】複数の物体をアニメーションさせる時に連動して動かない問題を解決する(iOS17)

Last updated at Posted at 2023-12-22

はじめに

iOS17でgeometryGroupという機能が追加されていました。
ドキュメントを見ても意味不明だったのですが、使ってみたら納得したので記事にしておきます。

やりたいこと

Simulator Screen Recording - iPhone 15 - 2023-12-22 at 20.04.04.gif

しかし、こうなってしまう

Simulator Screen Recording - iPhone 15 - 2023-12-22 at 20.03.30.gif

問題のある実装

import SwiftUI

struct ContentView: View {
    @State private var isMove = false

    var body: some View {
        VStack {
            ZStack {
                Circle()
                    .foregroundStyle(.red)
                    .frame(width: 100, height: 100)
                
                if isMove {
                    Circle()
                        .foregroundStyle(.blue)
                        .frame(width: 50, height: 50)
                }
            }
            .animation(.default, value: isMove)
            .offset(x: isMove ? 100 : -100)

            Button {
                isMove.toggle()
            } label: {
                Text("移動")
            }
        }
    }
}

解決方法

import SwiftUI

struct ContentView: View {
    @State private var isMove = false

    var body: some View {
        VStack {
            ZStack {
                Circle()
                    .foregroundStyle(.red)
                    .frame(width: 100, height: 100)
                
                if isMove {
                    Circle()
                        .foregroundStyle(.blue)
                        .frame(width: 50, height: 50)
                }
            }
+           .geometryGroup()
            .animation(.default, value: isMove)
            .offset(x: isMove ? 100 : -100)

            Button {
                isMove.toggle()
            } label: {
                Text("移動")
            }
        }
    }
}

おわり

ViewのGeometryを親Viewから分離してるらしいです。
むずいですね

公式ドキュメント

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?