非半透明的UITabBar创建奇怪的灰色条

mig*_*uan 2 swift swiftui

使用 SwiftUI,我有几个嵌套在 TabBar 内的 NavigationView。这样做的原因是我想更改每个 NavigationView 的标题以反映所选选项卡,但我找不到其他方法来执行此操作。另外,对于我的客户来说,UITabBar 的背景颜色为纯白色非常重要。为此我设置了UITabBar.appearance().isTranslucent = false,否则它显示为灰色。然而,一旦我这样做,我就会在 UITabBar 上方看到一条奇怪的灰线。我怎样才能摆脱这个?

struct ContentView: View {
    
    init() {
            
        UITabBar.appearance().backgroundColor = UIColor.white
        UITabBar.appearance().isTranslucent = false
    }
    
    var body: some View {
        TabView {

        NavigationView {
            
            Text("First tab")
                .padding(10)
                .background(Color.white)
                .navigationBarTitle(Text("First tab"), displayMode: .inline)
        }
        .tabItem {
            Text("First tab")
        }
            
        NavigationView {
            
            Text("Second tab")
                .padding(10)
                .background(Color.white)
                .navigationBarTitle(Text("Second tab"), displayMode: .inline)
        }
        .tabItem {
            Text("Second tab")
        }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

TabBar上方的灰色条

jva*_*ooy 6

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

UITabBar.appearance().backgroundColor = UIColor.white
UITabBar.appearance().isTranslucent = false
Run Code Online (Sandbox Code Playgroud)

用这些:

let tabBarAppearance = UITabBarAppearance()
tabBarAppearance.configureWithOpaqueBackground()
tabBarAppearance.backgroundColor = UIColor.white
UITabBar.appearance().standardAppearance = tabBarAppearance
Run Code Online (Sandbox Code Playgroud)

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