How can I set the background color of the whole view to a particular Color?
I tried different solutions, e.g.,
NavigationView {
ZStack {
Color.green
.edgesIgnoringSafeArea(.all)
}
...
}
which does nothing.
or
init{
UINavigationBar.appearance().backgroundColor = .green
}
which sets only the navigation bar (upper part) to the particular color
Here is my ContentView which looks as follows:
import TabularData
struct ContentView: View {
var model = DataModel.shared
@State private var searchText = ""
var body: some View {
NavigationView{
let headers: [String] = model.dataTable!.columns.map { $0.name }.sorted(by: <)
VStack{
List{
ForEach(headers.indices, id:\.self) { index in
if index != 0{
NavigationLink(destination: ActivityDetailView(header: headers[index])){
Text(headers[index])
}
.listRowBackground(
((index % 2 == 0) ? Color.white : Color("customYellow"))
.cornerRadius(10)
)
}
}
}.searchable(text: $searchText)
}
.navigationTitle("Choose Activity")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Addition
And if possible, I want to set a gradient for the whole view as background color
let backgroundGradient = LinearGradient(
gradient: Gradient(colors: [Color.green, Color.blue]),
startPoint: .top, endPoint: .bottom)
Your issue is not because of the NavigationView
but the fact that you have a List
.
Up until iOS 16 there had been no direct SwiftUI way of changing the background colour of a List
. You had to access the UITableView
appearance proxy and "remove" the background colour that way. Now there is a dedicated modifier for this: scrollContentBackground(_:)
.
Use either of these methods, dependant on the target version, to clear the default list background colour, and then set your own, like this:
// iOS 15 and earlier
init() {
UITableView.appearance().backgroundColor = .clear
}
List {
...
}
// iOS 16
.scrollContentBackground(.hidden)
// set background to any colour or gradient
.background(.linearGradient(colors: [.green, .red], startPoint: .top, endPoint: .bottom))