Home > Software engineering >  SwiftUI - TabView overlaps ove views
SwiftUI - TabView overlaps ove views

Time:09-26

I have a custom tabview:

import SwiftUI

struct CustomTabBar: View {
var animation: Namespace.ID
@Binding var currentTab: Tab
var body: some View {
    HStack(spacing: 0) {
        ForEach(Tab.allCases, id: \.rawValue) {tab in
            TabButton(tab: tab, animation: animation, currentTab: $currentTab) { pressedTab in
                withAnimation(.spring()) {
                    currentTab = pressedTab
                }
            }
        }
    }
}
}

struct TabButton: View {
var tab: Tab
var animation: Namespace.ID
@Binding var currentTab: Tab
var onTap: (Tab)->()

var body: some View {
    Image(tab.rawValue)
        .renderingMode(.original)
        .resizable()
        .frame(width: 27, height: 27)
        .foregroundColor(currentTab == tab ? .white : .gray)
        .frame(width: 50, height: 50 )
        .background(
            ZStack {
                if currentTab == tab {
                    Circle()
                        .fill(Color("startColor"))
                        .matchedGeometryEffect(id: "TAB", in: animation)
                }
            }
        )
        .frame(maxWidth: .infinity)
        .onTapGesture {
            onTap(tab)
        }
}
}

My Main View where I use the customTabBar:

import SwiftUI

struct MainView: View {

@State var currentTab : Tab = .Home
init() {
    UITabBar.appearance().isHidden = true
}
@Namespace var animation

var body: some View {
    ZStack(alignment: .bottom) {
        TabView(selection: $currentTab) {
            HomeView()
                .tag(Tab.Home)
            
            SearchView()
                .tag(Tab.Search)
            
            MessagesView()
                .tag(Tab.Messages)
            
            SettingsView()
                .tag(Tab.Settings)
        }
        CustomTabBar(animation: animation, currentTab: $currentTab)
    }
}
}

enum Tab: String, CaseIterable {
case Home = "Home"
case Search = "Search"
case Messages = "Messages"
case Settings = "Settings"
}


struct MainView_Previews: PreviewProvider {
static var previews: some View {
    MainView()
}
}

For Some reason the tab view is overlapping all the views (sitting on top)

enter image description here

it should sit like a VStack the view and then the tabview at the bottom and the view not overlapping

CodePudding user response:

First, I would wrap your custom tab bar as follows:

VStack {
    Spacer()
    CustomTabBar(animation: animation, currentTab: $currentTab)
}

Then on the TabView itself, you will likely need to pad the bottom to ensure it provides room for the custom view.

TabView(selection: $currentTab) {
    // Your views here
}.padding(.bottom, <<Height of the custom view, plus spacing here>>)
  • Related