Customize View Background & Border in SwiftUI
Written by Team Kodeco
As a developer, you want your app’s user interface to look great and feel intuitive. One way to achieve this is by customizing the background and border of your views in SwiftUI. In this cookbook entry, you’ll learn how to use modifiers to customize the appearance of views.
Let’s imagine you have a basic view with a text view:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.frame(width: 200, height: 50)
}
}
To customize the background of this view, you can use the background
modifier. For example, you can make the background of your text view red as follows:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.frame(width: 200, height: 50)
.background(Color.red)
}
}
The preview should look as follows:
You can also use an image as the background of your view. For example, try adding this to your Assets.xcassets and name it background:
Now update the code to set the background of the view to that image:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.frame(width: 200, height: 50)
.background(
Image("background")
.resizable(resizingMode: .tile)
.opacity(0.25)
)
.fontWeight(.heavy)
}
}
The preview should look as follows:
Let’s review the new lines added here:
-
Image("background")
: This creates an instance of Image with the specified image name “background”. The image name corresponds to the name you gave to the image file in the Assets.xcassets folder. -
.resizable(resizingMode: .tile)
: This modifier allows the specified image to adjust its size to fit the dimensions of its container. WithresizingMode: .tile
, the image repeats itself to fill the available space if the image’s original size is smaller than the view’s size. IfresizingMode
is not specified, the default behavior is.stretch
, which scales the image to fit its frame while maintaining the aspect ratio. -
.opacity(0.25):
: Theopacity
modifier sets the opacity of the view to the specified value. In this case, you set theopacity
to0.25
, making the background image slightly transparent.
To add a border to a view, you can use the border
modifier. For example, try adding a black border with a width of 2 points to your view:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.frame(width: 200, height: 50)
.background(
Image("background")
.resizable(resizingMode: .tile)
.opacity(0.25)
)
.fontWeight(.heavy)
.border(Color.black, width: 2)
}
}
The preview should look as follows:
By using the background
and border
view modifiers, you can customize the background and border of your views in SwiftUI. By combining these modifiers, you can make your app’s UI look polished and professional. Have fun experimenting with different colors and images to make your views unique and visually appealing!