SwiftUI:如何将 tabItems 在 TabView 中垂直居中?

问题描述 投票:0回答:1

我在 TabView 中添加了 5 个选项卡项。中间的是图像视图,其他的是文本视图。为什么它们不垂直居中?图像视图浮动在 TabView 之上。

这是代码,

struct ContentView: View {

    var body: some View {
        TabView {
            Text("")
                .tabItem {
                    Text("One")
                }
            Text("")
                .tabItem {
                    Text("Two")
                }
            Text("")
                .tabItem {
                    Image(systemName: "plus.app")
                }
            Text("")
                .tabItem {
                    Text("Three")
                }
            Text("")
                .tabItem {
                    Text("Four")
                }
        }
        .onAppear {
            let tabBarItemAppearence = UITabBarItemAppearance()

            let tabBarAppearance = UITabBarAppearance()
            tabBarAppearance.shadowColor = UIColor(.gray)
            tabBarAppearance.stackedLayoutAppearance = tabBarItemAppearence

            UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
        }
    }
}

#Preview {
    ContentView()
}

将文本视图替换为设置

systemImage
属性的标签视图后,标签视图中的图像似乎与图像视图对齐。

有没有办法让一般视图在 tabItems 中垂直居中?

ios swiftui tabview tabitem
1个回答
0
投票

实际上不能,TabBar 项默认包含图像和文本。它是为这种对齐而设计的。你需要自己定制一个View,比如:

struct ImageTabItem: View {
    let imageName: String
    let imageSize: CGSize

    var body: some View {
        Image(systemName: imageName)
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: imageSize.width, height: imageSize.height)
    }
}

struct TextTabItem: View {
    let tabName: String

    var body: some View {
        Text(tabName)
            .font(.footnote)
    }
}

struct CustomTabBar: View {
    var body: some View {
        GeometryReader { geo in
            ZStack {
                VStack {
                    Spacer()
                    HStack(spacing: 0) {
                        let tabWidth = geo.size.width / 5
                        TextTabItem(tabName: "One")
                            .frame(width: tabWidth)

                        TextTabItem(tabName: "Two")
                            .frame(width: tabWidth)

                        ImageTabItem(imageName: "plus.app", imageSize: .init(width: 30, height: 30))
                            .frame(width: tabWidth)

                        TextTabItem(tabName: "Three")
                            .frame(width: tabWidth)

                        TextTabItem(tabName: "Four")
                            .frame(width: tabWidth)
                    }
                }
            }
        }
    }
}

但是有很多缺点,比如:处理动作手势、safeArea padding等,必须自己去覆盖。

© www.soinside.com 2019 - 2024. All rights reserved.