UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Make Capsule() move when swiping between tabs - matchedGeometryEffect

Forums > SwiftUI

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.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.