I can't set a background color under ScrollView
in SwiftUI. When I use .background(Color.red)
the background is cut off so it doesn't go under navigation bar and scrolling seems to be broken.
I tried a couple of solutions but each of them doesn't work.
I have a simple view hierarchy
NavigationView {
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.navigationBarTitle("Title", displayMode: .large)
}
.navigationViewStyle(StackNavigationViewStyle())
it works as expected
now, I would like to add a background color, I tried the following solutions
NavigationView {
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.background(Color.red)
.navigationBarTitle("Title", displayMode: .large)
}
.navigationViewStyle(StackNavigationViewStyle())
result
NavigationView {
ZStack {
Color.red
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.navigationBarTitle("Title", displayMode: .large)
}
}
.navigationViewStyle(StackNavigationViewStyle())
result
NavigationView {
ZStack {
Color.red.edgesIgnoringSafeArea([.all])
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.navigationBarTitle("Title", displayMode: .large)
}
}
.navigationViewStyle(StackNavigationViewStyle())
result
How to set up a background color under ScrollView
packed in NavigationView
?
// edit:
The animation below presents a desirable effect (it is made with UIKit).
To change a navigation bar color in SwiftUI, you apply toolbarBackground modifier to the content view of NavigationStack . NavigationView is deprecated in iOS 16. toolbarBackground accepts two parameters. ShapeStyle : The style to display as the background of the bar.
There are two steps to change the SwiftUI list background color. Hide the standard background of the List. Set a new background color.
SwiftUI doesn't have a dedicated modifier for displaying background colors or images, but instead lets us specify any kind of background view using its background() modifier. To be clear, you can use any view as your background – another text view if you wanted, for example.
After exhausting all possibilities, I landed with the below solution which works perfectly for what you want to achieve.
struct DemoView: View {
init(){
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.backgroundColor = UIColor.red
UIScrollView.appearance().backgroundColor = UIColor.red
}
var body: some View {
NavigationView{
ScrollView{
VStack{
ForEach(0..<30, id: \.self){ _ in
Text("Text Text").foregroundColor(Color.black)
}
}.frame(maxWidth: .infinity)
.background(Color(UIColor.red))
}.navigationBarTitle("Title")
}
}
}
Hope this helps;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With