I am trying to recreate a segmented picker with customized buttons. My goal is that when switching the tab, the background smoothly transitions from the former active tab to the new active tab. it mostly works, but when I am trying to switch back (eg. from tab3 to tab2 or tab1), the animation is gone/ or does not work. Am I missing something?
struct CustomSegmentedPickerView: View {
private var titles = ["products", "causes", "info"]
private var colors = [Color.primaryAccent, Color.primaryAccent, Color.primaryAccent]
@State private var currentIndex: Int = 0
@Namespace var namespace
@Namespace var namespace2
var body: some View {
VStack (alignment: .center){
ZStack {
HStack {
ForEach (0 ..< titles.count) {index in
Button {
withAnimation(.default){
self.currentIndex = index
}
} label: {
ZStack {
if index == currentIndex {
Rectangle()
.frame(height: 40)
.cornerRadius(770)
.foregroundColor(
self.colors[self.currentIndex].opacity(0.3))
.matchedGeometryEffect(id: "background", in: namespace)
} else {
Rectangle()
.frame(height: 40)
.cornerRadius(770)
.matchedGeometryEffect(id: "background2", in: self.namespace2)
.foregroundColor(.clear)
}
Text(self.titles[index])
.foregroundColor(.black)
}
}
}
}
.padding()
}
}
}
}
I thought maybe I need a new namespace ID, but it does not change anything. Any help is appreciated. Thanks in advance!
BR