不透明的UITabBar创建奇怪的灰色条

问题描述

使用SwiftUI,我在TabBar内嵌套了几个NavigationViews。这样做的原因是,我想更改每个NavigationView的标题以反映所选的选项卡,而我找不到其他方法来做到这一点。同样,对UITabBar的背景颜色为纯白色对我的客户也非常重要。因此,我设置了files.forEach(el => { if (el.name.includes(fName)) { res.write(el.name + el.ext); } else { console.log('nothing') } }); res.end() ,否则它显示为灰色。但是,一旦这样做,我就会在UITabBar上方看到一条奇怪的灰色线。我该如何摆脱呢?

UITabBar.appearance().isTranslucent = false

Grey bar above TabBar

解决方法

        UITabBar.appearance().isTranslucent = false

是一种hack(有关TabView内部实现的未记录假设),它破坏了NavigationView的布局(删除了NavigationView具有活动约束的视图)

以下是可能的解决方法:

  1. 仅使用一个根NavigationView

demo

struct ContentView: View {

    init() {

        UITabBar.appearance().backgroundColor = UIColor.white
        UITabBar.appearance().isTranslucent = false
    }

    @State private var title = ""
    var body: some View {

        NavigationView {
            TabView {

                Text("First tab")
                    .padding(10)
                    .background(Color.white)
                    .onAppear {
                        self.title = "First tab"
                    }
                    .tabItem {
                        Text("First tab")
                }

                Text("Second tab")
                    .padding(10)
                    .background(Color.white)
                    .onAppear {
                        self.title = "Second tab"
                    }
                    .tabItem {
                        Text("Second tab")
                }
            }
            .navigationBarTitle(Text(title),displayMode: .inline)
        }
    }
}
  1. 创建自定义标签栏(使用HStack视图中的Button
,

作为Asperi回答中选项的另一种选择,您可以替换以下代码行:

UITabBar.appearance().backgroundColor = UIColor.white
UITabBar.appearance().isTranslucent = false

带有这些:

let tabBarAppearance = UITabBarAppearance()
tabBarAppearance.configureWithOpaqueBackground()
tabBarAppearance.backgroundColor = UIColor.white
UITabBar.appearance().standardAppearance = tabBarAppearance

它具有相同的效果,但是使用configureWithOpaqueBackground()而不是将isTranslucent设置为false可以保留NavigationView所依赖的约束。