Horitsu Potter
Horitsu Potter

Reputation: 117

I don't know to set a default TabBar

I want to set an image as the background of this TabBar I tried by many way but it can't enter image description here

Upvotes: 0

Views: 151

Answers (2)

Roman R
Roman R

Reputation: 51

you have to set it as a @State var like so:

@State var selectedTab: Int = 0

then:

TabView(selection: $selectedTab) {
            YourView()
                .tabItem{
                    VStack {
                        Text("First")
                    }
                }.tag(0)

then create YourView

Upvotes: 0

John Sorensen
John Sorensen

Reputation: 960

I have found the default SwiftUI TabBar to be tricky to work with, but luckily it's not too hard to make a custom TabBar. This lets you add images or any other View as the "tabs."

Example Code:

struct ContentView: View {
    @State var selectedTab: TabPicker.MenuTab = .first
    var body: some View {
        VStack {
            Text("Hello, World!")
        
            Spacer(minLength: 0)
            HStack {
                TabPicker(selectedTab: $selectedTab)
            }
        }
    }
}


struct TabPicker: View {
    enum MenuTab {
        case first
        case second
        case third
    }

    @Binding var selectedTab: MenuTab
    var body: some View {
        HStack {
        
   
            Spacer() // spacers ensure equal spacing between elements
            Text("1") // change these to be whatever views you need
                .fontWeight( selectedTab == .first ? .bold: .light) // some way of indicating which tab is selected
                .onTapGesture { selectedTab = .first }
            Spacer()
            Text("2")
                .fontWeight( selectedTab == .second ? .bold: .light)
                .onTapGesture { selectedTab = .second }
            Spacer()
            Text("3")
                .fontWeight( selectedTab == .third ? .bold: .light)
                .onTapGesture { selectedTab = .third }
            Spacer()
        }
    }
}

Upvotes: 1

Related Questions