SwiftUI:使用NavigationStack显示导航栏

xeufq47z  于 2023-04-28  发布在  Swift
关注(0)|答案(2)|浏览(174)

我想显示一个导航栏有一个橙子的背景颜色和白色的标题。
在此设置下一切正常:

let navigationBarAppearance = UINavigationBarAppearance()
    navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor(Color.white)]
    navigationBarAppearance.backgroundColor = .orange
    
    UINavigationBar.appearance().standardAppearance = navigationBarAppearance
    UINavigationBar.appearance().compactAppearance = navigationBarAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance

我的屏幕的源代码看起来像这样:

struct ScreenView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Row", destination: Text("Tapped on row"))
            }
        }
        .navigationTitle("List")
        .navigationBarTitleDisplayMode(.inline)
    }
}

结果:

如果我用NavigationStack替换NavigationView,导航栏就会消失。
我错过了什么吗?

gudnpqoy

gudnpqoy1#

您必须将.navigationTitle()修改器应用于NavigationStack内部的视图

NavigationStack {
        List {
            NavigationLink("Row", destination: Text("Tapped on row"))
        }
        .navigationTitle("List")
        .navigationBarTitleDisplayMode(.inline)
    }

这似乎解决了这个问题。

jhiyze9q

jhiyze9q2#

仅使用SwiftUI和NavigationStack,您可以在橙子背景上实现白色标题文本,使用以下代码。

struct ScreenView: View {
    var body: some View {
        NavigationStack {
            List {
                NavigationLink("Row", destination: Text("Tapped on row"))
            }
            .toolbar {
                ToolbarItem(placement: .principal) { Text("List").foregroundColor(.white) }
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbarBackground(Color.orange, for: .navigationBar)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ScreenView()
    }
}

相关问题