1

When using TabView in SwiftUI, what can I do to show the selected Tab like in the following picture?

enter image description here

I've tried creating a VStack within each tab like this:

struct ContentView: View {
@State public var tabViewSelection = 0
var body: some View {
    TabView(selection: $tabViewSelection) {
        HomeFirstLevel()
            .tabItem {
                VStack {
                    Image("HomeIcon")
                    Rectangle()
                        .frame(height: 7)
                        .foregroundColor((tabViewSelection == 0) ? .black : .clear)
                }
            }.tag(0)
        }
    }
}

But it's not working. I can't even seem to add a Rectangle instead of an Image:

HomeFirstLevel()
   .tabItem {
       Rectangle()
   }.tag(0)

Does TabView not accept shapes? Thanks in advance for the help!

1 Answer 1

6

You can not set shape in tabItem. But you can use ZStack to add shape over the tab bar and set the x position.

Here is the demo.

struct ContentViewTabDemo: View {
    @State public var tabViewSelection = 0
    
    private var singleTabWidth = UIScreen.main.bounds.width / 5
    
    var body: some View {
        ZStack(alignment: .bottomLeading) {
            TabView(selection: $tabViewSelection) {
                Color.red
                    .tabItem {
                        VStack {
                            Image(systemName: "circle.fill")
                        }
                    }.tag(0)
                
                Color.blue
                    .tabItem {
                        VStack {
                            Image(systemName: "heart.fill")
                        }
                    }.tag(1)
                
                Color.red
                    .tabItem {
                        VStack {
                            Image(systemName: "circle.fill")
                        }
                    }.tag(2)
                
                Color.blue
                    .tabItem {
                        VStack {
                            Image(systemName: "heart.fill")
                        }
                    }.tag(3)
                
                Color.red
                    .tabItem {
                        VStack {
                            Image(systemName: "circle.fill")
                        }
                    }.tag(4)
            }
            
            Rectangle()
                .offset(x: singleTabWidth * CGFloat(tabViewSelection))
                .frame(width: singleTabWidth, height: 7)
                .padding(.bottom, 2)
                .animation(.default)
        }
    }
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.