Home > Software engineering >  SwiftUI use TabView with Picker
SwiftUI use TabView with Picker

Time:09-16

I'm trying to use a Picker to change the selected tab.

The issue is that when I tap on the picker, the content changes without animation.

Scrolling between tabs works correctly (the picker animates accordingly).

enter image description here

struct ContentView: View {
@State var tabSelectedValue = 0

var body: some View {

    VStack {
        
        Picker("", selection: $tabSelectedValue) {
            Text("First").tag(0)
            Text("Second").tag(1)
        }
        .pickerStyle(SegmentedPickerStyle())
        .padding()
         
        TabView(selection: $tabSelectedValue) {
         
            Text("Content for first tab")
                .tag(0)
        
            Text("Content for second tab")
                .tag(1)
            
            
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
    }
    .padding()
}

}

CodePudding user response:

Picker with SegmentedPickerStyle have default animation. So when you change the tab it's animating Picker. To animate TabView when you change tabSelectedValue you need to add the animation ViewModier to your TabView. Add animation(_:value:) modifier to your TabView.

.animation(.easeIn, value: tabSelectedValue)
  • Related