How To Set NavigationView Background Colour in Swi

2020-02-06 13:04发布

问题:

I'm trying to set the background color of a NavigationView. I'm trying by adding a ZStack using the code below (partly from the SwiftUI tutorial). Yet it's only ever white unless I replace NavigationView... with Spacer()

    var body: some View {
    ZStack
        {
            NavigationView {
                List {
                    Toggle(isOn: $userData.showFavoritesOnly) {
                        Text("Favourites")
                    }
                    ForEach(userData.landmarks) { landmark in
                        if !self.userData.showFavoritesOnly || landmark.isFavorite {
                            NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
                                LandmarkRow(landmark: landmark)
                            }
                        }
                    }
                }

                .navigationBarTitle(Text("Landmarks"), displayMode: .large)
            }

    }.background(Color.blue.edgesIgnoringSafeArea(.all))
}

I can set the individual list item color but i want the whole background to show blue

回答1:

It is same as UINavigationBar. But since there is no direct api yet, you can change it using appearance:

UINavigationBar.appearance().backgroundColor = .orange
UINavigationBar.appearance().tintColor = .green
UINavigationBar.appearance().barTintColor = .yellow
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.red]
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.red]

You should put this somewhere that you sure the compiler reads like inside the init() method.

Note that some of these will not work below Xcode 11 beta 5.