How do I add a sliding header to my Page View in Swift UI

Viewed 135

I'm trying to add a header to my app depending on current Tab, so First, Second, Third Fourth. Similar to the reddit app News/Popular/Home. Is there something in Swift UI that can do this?

enter image description here

    var body: some View {
            TabView {
                Text("First")
                Text("Second")
                Text("Third")
                Text("Fourth")
            }
            .tabViewStyle(.page(indexDisplayMode: .never))
        }
}

1 Answers

You can put your own buttons above the TabView, that change the selected page:

struct ContentView: View {
    
    @State private var selectedTab = 1
    
    var body: some View {
        VStack(spacing: 0) {
            
            HStack {
                tabButton(title: "One", tag: 1)
                tabButton(title: "Two", tag: 2)
                tabButton(title: "Three", tag: 3)
            }
            .padding(.top)
            .font(.headline)
            
            TabView(selection: $selectedTab) {
                Text("First Tab").tag(1)
                Text("Second Tab").tag(2)
                Text("Third Tab").tag(3)
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            .background(.gray.opacity(0.5))
        }
    }
    
    func tabButton(title: String, tag: Int) -> some View {
        VStack {
            Button(title) { withAnimation { selectedTab = tag } }
            .frame(maxWidth: .infinity)
            .foregroundColor(selectedTab == tag ? .primary : .secondary)
            
            Color(selectedTab == tag ? .blue : .clear)
                .frame(height: 4)
                .padding(.horizontal)
        }
    }
}

enter image description here

Related