I can't change background color of a view if i List static items. this my code:
NavigationView {
ZStack {
Color("AppBackgroundColor").edgesIgnoringSafeArea(.all)
List {
Section(header: Text("Now in theaters")) {
ScrollMovies(type: .currentMoviesInTheater)
}
Section(header: Text("Popular movies")) {
ScrollMovies(type: .popularMovies)
}
}.listStyle(.grouped)
}
}
@State var users: [String] = ["User 1",
"User 2",
"User 3",
"User 4"]
init(){
UITableView.appearance().backgroundColor = .red
UITableViewCell.appearance().backgroundColor = .red
UITableView.appearance().tableFooterView = UIView()
}
var body: some View {
List(users, id: \.self){ user in
Text(user)
}
.background(Color.red)
}
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
Easiest way to do this for now is just to use UIAppearance proxy. SwiftUI is young so there's a couple of features not fully implemented correctly by Apple yet.
UITableView.appearance().backgroundColor = .red
All SwiftUI's List
s are backed by a UITableView
in iOS. so you need to change the background color of the tableView. But since Color
and UIColor
values are slightly different, you can get rid of the UIColor
.
struct ContentView: View {
init(){
UITableView.appearance().backgroundColor = .clear
}
var body: some View {
Form {
Section(header: Text("First Section")) {
Text("First cell")
}
Section(header: Text("Second Section")) {
Text("First cell")
}
}
.background(Color.yellow)
}
}
Now you can use Any background (including all Color
s) you want
Note that those top and bottom white areas are the safe areas and you can use the .edgesIgnoringSafeArea()
modifier to get rid of them.
Also note that List
with the .listStyle(GroupedListStyle())
modifier can be replaced by a simple Form
. But keep in mind that SwiftUI controls behave differently depending in their enclosing view.
You can provide a modifier for the items in the list
NavigationView {
ZStack {
Color("AppBackgroundColor").edgesIgnoringSafeArea(.all)
List {
Section(header: Text("Now in theaters")) {
ScrollMovies(type: .currentMoviesInTheater)
.listRowBackground(Color.blue) // << Here
}
Section(header: Text("Popular movies")) {
ScrollMovies(type: .popularMovies)
.listRowBackground(Color.green) // << And here
}
}.listStyle(.grouped)
}
}
since, you are asking for changing the background color of view,
you can use .colorMultiply()
for that.
Code:
var body: some View {
VStack {
ZStack {
List {
Section(header: Text("Now in theaters")) {
Text("Row1")
}
Section(header: Text("Popular movies")) {
Text("Row2")
}
/*Section(header: Text("Now in theaters")) {
ScrollMovies(type: .currentMoviesInTheater)
}
Section(header: Text("Popular movies")) {
ScrollMovies(type: .popularMovies)
} */
}.listStyle(.grouped)
}.colorMultiply(Color.yellow)
}
}
Output: