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 this is always an issue.
struct Person : Identifiable{
var id : Int
var name : String
}
struct ContentView: View {
let people = [
Person(id: 1, name: "Ricky"),
Person(id: 2, name: "Dani"),
Person(id: 3, name: "Mark"),
Person(id: 4, name: "Kailin"),
Person(id: 5, name: "James"),
Person(id: 5, name: "Jenna")
]
var body: some View {
NavigationView{
ZStack{
Color.red
.edgesIgnoringSafeArea(.all)
ScrollView{
ForEach(people, id: \.id) { person in
Text(person.name)
.frame(width: 300, height: 400)
.background(Color.blue)
.padding()
}
}.navigationBarTitle("Home")
}
}
}
// init(){
// UIView.appearance().backgroundColor = .orange
// }
}
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.
navigationBar. barTintColor = UIColor. newBlueColor() and of course this just changes the colour of the navigation bar of the view controller that the code is within.
We can change the background color of a list row in SwiftUI with listRowBackground(_:) modifier. To set a list row background color, add listRowBackground(_:) modifier to the list row item.
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.
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