Setting background color in SwiftUI views is a trivial task. However, if you haven’t done it before, then you might find yourself scratching your head about it. So here I’m going to suggest two different ways to do so.
There is something that we have to make clear before I showcase anything; in SwiftUI there is not a single property that sets the background color. To achieve that, we have to use the Color struct, which is also a View.
The first, and probably more preferable way to set a background color is to use a ZStack. The first view in the stack must be the Color object; all the rest view contents should be laid out properly on top of the Color view. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var body: some View { ZStack { Color(UIColor.systemIndigo) .ignoresSafeArea() Text(“Custom background color\nwith a ZStack”) .multilineTextAlignment(.center) .foregroundColor(.white) .font(.title2) } } |
Notice that applying the ignoresSafeArea
modifier is necessary so the Color view to be expanded out of the safe area limits of the device. If you avoid calling it, then the background in the safe area will be according to the device’s color scheme like that:
Another thing to note is that the ignoresSafeArea
modifier is available in iOS 14 and above. If you aim to deploy your app in a lower iOS version then replace that modifier with the following:
1 2 3 4 |
Color(UIColor.systemIndigo) .edgesIgnoringSafeArea(.all) |
edgesIgnoringSafeArea
works in iOS 13 as well, just make sure to pass the .all
value as argument so the Color view to exceed all safe area boundaries.
The second way to set a background color is in combination with the GeometryReader view. In that case, the Color view must be given as argument to a background
view modifier, which must be applied to the GeometryReader view:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var body: some View { GeometryReader { geometry in Text(“Custom background color\nwith a GeometryReader”) .multilineTextAlignment(.center) .foregroundColor(.white) .font(.title2) .position(x: geometry.size.width/2, y: geometry.size.height/2) } .background(Color(UIColor.brown) .ignoresSafeArea()) } |
The above results to this:
The position
modifier is necessary in order to position the sample Text to the center of the screen.
So, this is it! Choose the way you prefer or suits your implementation, and set background colors to your SwiftUI views easily. Thank you for reading!