Set SwiftUI backgroundColor the same way as foregroundColor

Daily Coding Tip 009

It’s useful that SwiftUI has a modifier called .background() so that you can add any kind of view behind the current view. Instead of being limited to colour, your background could be an image or a more complicated shape. But when I use the .foregroundColor() modifier, I take advantage of the fact that a Color is expected by giving a parameter like .blue. You can’t do the same with .background(), because the background could be any kind of view.

extension View {
func backgroundColor(_ color: Color) -> some View {
return self.background(color)
}
}
struct ContentView: View {
var body: some View {
Rectangle()
.backgroundColor(.blue)
}
}

This extension makes it easier to add a background colour to a view.

I find myself adding colours as backgrounds more often, so this is useful to me. If you want to have a more complicated view as a background, I would suggest using a ZStack. This gives you more flexibility in terms of allowing multiple layers, instead of a main view and a background. The .overlay() modifier has a similar purpose, giving you the ability to add a view in front of your existing view.

My advice for this modifier is the same, as I think a ZStack is more flexible in almost any situation I can think of.


Get more Daily Coding Tips in your inbox!