I have the matchedGeo working moving forward but for some reason, it doesn't work if I select a text moving backward. I have included a screenshot gif so you can see the issue.
import SwiftUI
enum CapsuleNavTitles: String, CaseIterable {
case Discussion = "Discussion"
case About = "About"
case Memebers = "Members"
}
struct CapsuleNavAnimationComponent: View {
@State var currentNav: CapsuleNavTitles = .Discussion
@Namespace var animation
var body: some View {
CapsuleNav()
}
@ViewBuilder
func CapsuleNav() -> some View {
HStack() {
ForEach(CapsuleNavTitles.allCases, id: \.rawValue) { nav in
Text(nav.rawValue)
.padding(EdgeInsets(top: 9, leading: 17, bottom: 9, trailing: 17))
.background(currentNav == nav ? Capsule()
.fill(Color.buttonColor)
.matchedGeometryEffect(id: "CapsuleNavTitles", in: animation) : nil)
.foregroundColor(currentNav == nav ? .white : .black)
.onTapGesture {
withAnimation(.easeInOut) {
currentNav = nav
}
}
}
}
.background(Capsule().fill(Color.mainColor))
}
}

There might be a more reliable way to use
matchedGeometryEffect. I would suggest, theCapsulethat you are applying in the background should be matched to one of the nav items. The item that has been selected is treated as the source, theCapsuleitself is never the source.The version below has the following changes:
matchedGeometryEffeectmodifier has been added to each of the nav items, using the enum as id.Capsuleis now an overlay over the background.Capsuleadopts the current selection as its id for thematchedGeometryEffect.Capsulealways hasisSource = false.Here you go: