how to animate transition between vstack into hstack in swiftui?

Asked on 2024-11-18

1 search

To animate a transition between a VStack and an HStack in SwiftUI, you can use the AnyLayout type to dynamically switch between different layouts based on certain conditions, such as accessibility settings or other state changes. This approach allows you to create a smooth transition between different stack layouts.

Here's a basic example of how you might implement this:

import SwiftUI

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

    var body: some View {
        VStack {
            Toggle("Horizontal Layout", isOn: $isHorizontal)
                .padding()

            if isHorizontal {
                HStack {
                    Text("Item 1")
                    Text("Item 2")
                    Text("Item 3")
                }
                .transition(.slide)
            } else {
                VStack {
                    Text("Item 1")
                    Text("Item 2")
                    Text("Item 3")
                }
                .transition(.slide)
            }
        }
        .animation(.default, value: isHorizontal)
    }
}

In this example, a Toggle is used to switch between a VStack and an HStack. The .transition(.slide) modifier is applied to animate the change, and .animation(.default, value: isHorizontal) ensures that the transition is animated whenever the isHorizontal state changes.

For more advanced transitions and animations, you can refer to the session Enhance your UI animations and transitions (08:10) from WWDC 2024, which covers new high-level transitions and integration between SwiftUI animations and UIKit.