Customize your container views in SwiftUI with containerBackground

AsyncLearn
2 min readMar 4, 2024

--

Now you can add a background to your container views in your watchOS applications using the containerBackground(_:for:) modifier.

You can use it in container views like TabView and NavigationStack. Let's see an example using a TabView in watchOS:

TabView {
Text("Yellow")
.containerBackground(.yellow.gradient, for: .tabView)
Text("Red")
.containerBackground(.red.gradient, for: .tabView)
}
.tabViewStyle(.verticalPage)

Here, we configure our elements by applying a containerBackground(_:for:) to each tab. Note that we are assigning the colors red and yellow followed by the gradient property. This automatically tries to use a gradient that makes reading the content easier using the specified color as the base.

Although we only use colors, we can pass any object conforming to ShapeStyle.

Navigating vertically in a TabView in a watchOS application.

Now let’s see how it looks when using a NavigationStack:

NavigationStack {
List {
NavigationLink("Main") {
Text("Blue")
.containerBackground(.blue.gradient, for: .navigation)
}
NavigationLink("Second") {
Text("Green")
.foregroundStyle(.green)
.containerBackground(for: .navigation) {
Image(.background)
.resizable()
}
}
}
}

Here, we use NavigationStack, and the elements are organized within a List, each of which is a NavigationLink. This allows us to have a master-detail flow. We see that the parameter for indicates that it is navigation. We need to specify this when we want to use containerBackground(_:for:) on elements within a NavigationStack.

Another important detail is that for the second NavigationLink, instead of a color, we are passing an image. This is possible thanks to another constructor of the containerBackground modifier, containerBackground(for:alignment:content:). This accepts a closure that can return any View.

Navigating a watchOS application using NavigationStack.

If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/personaliza-tus-contenedores-en-swiftui-con-container-background/

--

--

AsyncLearn

Stay up-to-date in the world of mobile applications with our specialised blog.