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 you do this using SwiftUI
?
SwiftUI – How to change the background color of a View
backgroundbackground-colormodifierswiftuiview
Related Topic
- Android – Animate change of view background color on Android
- Node.js – How to run a node.js app as a background service
- CSS: background image on background color
- Css – the difference between background and background-color
- Html – How to make div background color transparent in CSS
- Html – Change select box option background color
- Android – How to make gradient background in android
- SwiftUI: How to pop to Root view
Best Answer
Screen's Background Color
(As of Xcode Version 13)
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.
Using ZStack
I added
.ignoresSafeArea()
otherwise, it will stop at safe area margins.Using Overlay Modifier
Note: It's important to keep the
.ignoresSafeArea
on just the color so your main content isn't ignoring the safe area edges too.iOS 15
iOS 15/Xcode 13 has introduced some changes to the way Styles work with the edges of safe areas.
From my observation, the rule is: If the style touches the safe area edge, it will bleed into the safe area.
This gives you more options for setting a background color/style.
What is a Style?
A Style can be:
Using Background
Because the background of the
VStack
touches the edge of the safe area, the purple color will bleed into the safe area.TabView
In iOS 15 the TabView is no longer translucent. Meaning the background color will bleed right into it.
If you want to provide a custom style for your TabView, you can add another Style that touches the bottom safe area edge so that bleeds into your TabView. For example:
NavigationView
The same thing that happens to TabView will also happen with NavigationView.
To customize the NavigationView style, add a style that will touch the top safe area edge and it will bleed into the NavigationView:
I'm totally open to other ways of accomplishing this. Leave a comment or edit this answer if you know of other ways.