【问题标题】:SwiftUI - TabView overlaps ove viewsSwiftUI - TabView 与视图重叠
【发布时间】:2021-09-24 17:06:42
【问题描述】:

我有一个自定义标签视图:

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)
        }
}
}

我使用 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()
}
}

由于某些原因,选项卡视图与所有视图重叠(位于顶部)

它应该像 VStack 一样放置视图,然后是底部的 tabview,并且视图不重叠

【问题讨论】:

  • 只需将ZStack(alignment: .bottom) { 替换为VStack {

标签: swift swiftui


【解决方案1】:

首先,我会将您的自定义标签栏包装如下:

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

然后在 TabView 本身上,您可能需要填充底部以确保它为自定义视图提供空间。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多