I\'m beginning to try out SwiftUI
and I\'m surprised that it doesn\'t seem to be straightforward to change the background color of a View
. How do y
You can Simply Change Background Color of a View:
var body : some View{
VStack{
Color.blue.edgesIgnoringSafeArea(.all)
}
}
and You can also use ZStack :
var body : some View{
ZStack{
Color.blue.edgesIgnoringSafeArea(.all)
}
}
var body: some View {
var body: some View {
NavigationView {
ZStack {
// Background
Color.blue.edgesIgnoringSafeArea(.all)
content
}
//.navigationTitle(Constants.navigationTitle)
//.navigationBarItems(leading: cancelButton, trailing: doneButton)
//.navigationViewStyle(StackNavigationViewStyle())
}
}
}
var content: some View {
// your content here; List, VStack etc - whatever you want
VStack {
Text("Hello World")
}
}
The code on Scene delegate in Swift UI
Content view background-color
window.rootViewController?.view.backgroundColor = .lightGray
I like to declare a modifier for changing the background color of a view.
extension View {
func background(with color: Color) -> some View {
background(GeometryReader { geometry in
Rectangle().path(in: geometry.frame(in: .local)).foregroundColor(color)
})
}
}
Then I use the modifier by passing in a color to a view.
struct Content: View {
var body: some View {
Text("Foreground Label").foregroundColor(.green).background(with: .black)
}
}
(As of Xcode Version 12)
I'm not sure if the original poster meant the background color of the entire screen or of individual views. So I'll just add this answer which is to set the entire screen's background color.
var body: some View {
ZStack
{
Color.purple
.ignoresSafeArea()
// Your other content here
// Other layers will respect the safe area edges
}
}
I added .ignoresSafeArea()
otherwise, it will stop at safe area margins.
var body: some View {
Color.purple
.ignoresSafeArea(.vertical) // Ignore just for the color
.overlay(
VStack(spacing: 20) {
Text("Overlay").font(.largeTitle)
Text("Example").font(.title).foregroundColor(.white)
})
}
Note: It's important to keep the .ignoresSafeArea
on just the color so your main content isn't ignoring the safe area edges too.
Use Below Code for Navigation Bar Color Customization
struct ContentView: View {
@State var msg = "Hello SwiftUI