Im trying to have a colored background while using a scrollview with SwiftUI but this causes the navigation title to no longer collapse. I\'ve tried a number of ways yet thi
Here is the solution I came up with... this solution also allows you to colour the background cells a different colour to your List Elements. You could do a very similar thing with ScrollView
As mentioned in the comments for the other solution, carrying out that solution with ListView leaves a bunch of whitespace from the cells. (Which is why this is useful)
I thought I would add to this as none of the other solutions worked for me.
struct ListBackgroundColor: ViewModifier {
let color: UIColor
func body(content: Content) -> some View {
content
.onAppear() {
UITableView.appearance().backgroundColor = self.color
//(Optional) Edit colour of cell background
UITableViewCell.appearance().backgroundColor = self.color
}
}
}
extension View {
func listBackgroundColor(color: UIColor) -> some View {
ModifiedContent(content: self, modifier: ListBackgroundColor(color: color))
}
}
UI Example https://imgur.com/a/TQ9c5Sc
Rearrange your views like this:
var body: some View {
NavigationView {
ScrollView {
ZStack {
Color.red
VStack {
ForEach(people, id: \.id) { person in
Text(person.name)
.frame(width: 300, height: 400)
.background(Color.blue)
.padding()
}
}
}
}.navigationBarTitle("Home")
}
NOTE THAT You can use UINavigationBar.appearance().backgroundColor = .red
alongside with another UIColor
like Color(UIColor.red)
for the background to simulate the transparent large NavigationBar
until the direct API for changing the proper colors in SwiftUI arrives.
And NOTE THAT UIColor.red
is slightly different with Color.red
.
Also NOTE THAT if you want to use a List
instead of ScrollView
, you should add .listRowInsets(EdgeInsets())
to ZStack
to get rid of the extra white space.