Reputation: 866
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 a simple view to 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)
})
}
}
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 actual tab content). The onAppear
and onDisapear
are called as expected hence all transition should be triggered.
If someone has an idea to start working with I would be very happy
Thanks
Upvotes: 3
Views: 4147
Reputation: 6500
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}
}
}
Upvotes: 5