Hi, I'm implementing a swiping tab view using SwiftUI's PageTabViewStyle()
tabView style, similar to, say, Reddit mobile. On the top are all the tab names which turn blue, and right under a small Capsule()
which moves to the selected tab. I'm having difficulty making the capsule move using matchedGeometryEffect()
when the user has gone to a new tab, however.
// The parent view
@State private var selectedTab: Category = .all
// [...]
VStack(spacing: 0) {
HistoryNavigationBar(selectedTab: $selectedTab)
TabView(selection: $selectedTab) {
ForEach(Category.allCases, id: \.self) { category in
HistoryList(category: category)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
With the important parts of HistoryNavigationBar
being:
@Namespace private var animation
// [...]
ForEach(History.Category.allCases, id: \.self) { category in
VStack(alignment: .leading, spacing: 5) {
Button(action: { selectedTab = category }) {
Text(category.rawValue.capitalized)
.foregroundColor(selectedTab == category ? .blue : .gray)
}
Capsule()
.frame(width: 20, height: 2)
.foregroundColor(selectedTab == category ? .blue : .clear)
}
}
How should I implement matchedGeometryEffect()
to get the desired effect of the capsule moving every time the tab is changed? I tried all sorts of combinations with matchedGeometryEffect()
(putting it after the capsule, putting the capsule in an if-statement, etc.), but to no success – whenever I swipe between tabs, or click on one of the tab names, the capsule just jumps to that tab.