Customize your container views in SwiftUI with containerBackground
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
.
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
.
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/