首页 > 解决方案 > SwiftUI - 基于设备的自定义 TabBar 高度

问题描述

在此处输入图像描述

我正在尝试根据设备设置自定义 TabBar 的高度,我的代码:

struct MyTabBar: View {
    @Binding var index: Int

    var body: some View {
        HStack {
            Button(action: {
                self.index = 0
            }) {
                Image(ImageText.iconHome.image)
            }

            Spacer(minLength: 0)

            Button(action: {
                self.index = 1
            }) {
                Image(ImageText.iconBell.image)
            }

            Spacer(minLength: 0)

            Button(action: {
                self.index = 2
            }) {
                Image(ImageText.iconAdd.image)
            }

            Spacer(minLength: 0)

            Button(action: {
                self.index = 3
            }) {
                Image(ImageText.iconSearch.image).foregroundColor(Color.red)
            }

            Spacer(minLength: 0)

            Button(action: {
                self.index = 4
            }) {
                Image(ImageText.iconHamburger.image)
            }

        }.padding(.horizontal, 26).frame(height: 56)
    }
}

如果设备有缺口,如何将自定义 TabBar 设置为更高的高度?SwiftUI 是否有一些在这里有用的东西?

标签: swiftswiftuitabbar

解决方案


您可以使用该GeometryReader元素访问安全区域插图,并将其添加为填充使用.safeAreaInsets.bottom(请注意,Xcode 自动完成几乎从不处理GeometryProxy属性):

var body: some View {
    GeometryReader { proxy in
        VStack {
            // Content goes here
            Spacer()

            // Custom tab bar
            HStack {
                Spacer()
                Button(action: {}) {
                    Image(systemName: "house.fill")
                    .padding()
                }
                Spacer()
                Button(action: {}) {
                    Image(systemName: "house.fill")
                    .padding()
                }
                Spacer()
                Button(action: {}) {
                    Image(systemName: "house.fill")
                    .padding()
                }
                Spacer()
                Button(action: {}) {
                    Image(systemName: "house.fill")
                    .padding()
                }
                Spacer()
            }
            .padding(.bottom, proxy.safeAreaInsets.bottom)
            .background(Color.red)

        }
    }.edgesIgnoringSafeArea(.bottom)
}

推荐阅读