How to Set Text Background Color in iOS SwiftUI

In this blog post, we’re taking a closer look at a fundamental yet potent way to enhance the look and feel of your mobile apps – setting text background color in SwiftUI. Assigning a background color can enrich your design and elevate your user interface’s overall appeal.

Basics: Set the Background Color

Applying a background color to a text view in SwiftUI is incredibly straightforward. The background() modifier is your go-to function for this purpose. Here’s a simple example:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!")

In the above example, the text “Hello, SwiftUI!” is presented with a yellow background color.

SwiftUI text background

Using Predefined and Custom Colors

SwiftUI allows you to use both predefined and custom colors as your text background. You can use any of the preset colors like .red, .green, .blue, etc., or define your own unique color:

Text("Hello, SwiftUI!")
    .background(Color(red: 0.1, green: 0.9, blue: 0.7))

In this code snippet, we have created a custom color for the text background using RGB values.

swiftui text background color

Rounded Corners for Background

Often, you might want a background color with rounded corners for your text. This is where the .clipShape() and RoundedRectangle() functions come into play:

Text("Hello, SwiftUI!")
    .clipShape(RoundedRectangle(cornerRadius: 10))

In the above example, the .padding() modifier ensures that the background color extends beyond the text edges, while clipShape(RoundedRectangle(cornerRadius: 10)) rounds the corners of the background.

SwiftUI Text background color

Setting text background color in SwiftUI is a powerful way to enhance the look of your app, highlight important information, and make your UI more dynamic and attractive. With SwiftUI, you have complete control over color customization and styling, so go ahead and make your app as colorful as you wish.

Similar Posts

One Comment

Leave a Reply