Building Twitter's Search tab in SwiftUI: Part 2
In my last post we started building Twitter’s Search tab and left off by finishing the header view.
Today we’ll expand on this to include the pages for each tab. We need a horizontally swiping view that has pages sized to the width of each screen. This is similar to a UIPageViewController in UIKit and, starting in iOS 14, SwiftUI has a native component for it. Its built-in to TabView as a TabViewStyle.
Just like our HeaderView, the PagerView is going to need to know the currently selected tab and a list of all tabs.
A few things to note here:
We pass selectedTab into the TabView as a Binding. This will cause selectedTab to update when the TabView changes pages.
We need to tag the contents of each page view (Text in our case), so TabView knows what value to assign to the selectedTab binding mentioned in 1.
The .tabViewStyle(.page) modifier tells the TabView to behave as a horizontally swiping list of pages and indexDisplayMode: .never hides the built-in page control that comes with it (the carousel dot indicators showing what page you’re on)
Now we can combine PagerView with our HeaderView.
If we run that it looks great, but with one problem. The header and pages aren’t linked together in any way.
HeaderView and PagerView are each maintaining their own state, and list of tabs, so let’s fix that. By switching each of their selectedTab variables from being State to Binding, they’ll no longer maintain ownership over the current tab.
Note how in the parameters for the Header/PagerView we pass in selectedTab as a binding with the $ notation, just like with the TabView. Now whether the selectedTab value is changed by the HeaderView or PagerView it will update in both places.
🎉 That’s it for this series. SwiftUI makes setting up this UI infrastructure so quick and easy, with such little code.
Thanks for reading, the entire TabbedPagerView source is available on my github here. Comment below if there’s something you’d like to see written about next!
Amazing! In the Twitter app, the tab bar automatically scrolls when swiping between tabs if the bar is wider than the screen - any idea how to implement that?