Setting Background Color in SwiftUI Views

Posted in SwiftUI

Updated on March 4th, 2021

⏱ Reading Time: 2 mins

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:

SwiftUI view background color with a ZStack

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:

SwiftUI view background color with a ZStack and no safe area

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:

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:

The above results to this:

SwiftUI view background color with a GeometryReader

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!

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on SerialCoder.dev.

    We respect your privacy. Unsubscribe at any time.