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
// }
}
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")
}
You can change the color of the navigation bar natively with the following modifier:
.toolbarBackground(.yellow, in: .navigationBar)
This works only on inline navigation bar (with a seamless animation)
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.
NOTE 1: UIColor.red
is slightly different with Color.red
.
NOTE 2: 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.