SwiftUI TabView Animation

Viewed 1333

I am currently facing a pb on my app. I would like to animate the insertion and removal of items that are controlled by SwiftUI TabView.

Here is the simplest view I can come with that reproduce the problem

struct ContentView: View {
    @State private var selection: Int = 1
    var body: some View {
        TabView(selection: $selection.animation(),
                content:  {
                    Text("Tab Content 1")
                        .transition(.slide) //could be anything this is for example
                        .tabItem { Text("tab1") }.tag(1)
                        .onAppear() {print("testApp")}
                        .onDisappear(){print("testDis")}
                    Text("Tab Content 2")
                        .transition(.slide)
                        .tabItem { Text("tab2") }.tag(2)
                })
       
    }
}

Actually when hitting a tabItem. It switches instantly from "Tab Content 1" to "Tab Content 2" and I would like to animate it (not the tab item button the actuel tab content). The On Appear and onDisapear are corectly called as expected hence all transition should be triggered.

If someone has an idea to start working with I would be very happy

Thanks

1 Answers

1.with .transition() we only specify which transition should happen.

2.Transition occur (as expected), only when explicit animation occurs.

3.Animation occurs when change happened(State, Binding)

here is one of possible approaches.

    struct ContentView: View {
        @State private var selection: Int = 1
        var body: some View {
            TabView(selection: $selection,
                    content:  {
                        ItemView(text:"1")
                            .tabItem { Text("tab1") }.tag(1)
                        ItemView(text: "2")
                            .tabItem { Text("tab2") }.tag(2)
                    })
            
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    
    
    struct ItemView: View {
        let text: String
        @State var hidden = true
        
        var body: some View {
            VStack {
                if !hidden {
                    Text("Tab Content " + text)
                        .transition(.slide) 
                }
            }
            .onAppear() { withAnimation {
                hidden = false
            }}
            .onDisappear(){hidden = true}
            
        }
    }

Related