How to Add Multicolor Text in iOS SwiftUI

In this blog post, we’re exploring an aspect of SwiftUI that can significantly enrich your app’s visual design – using multiple colors in a single SwiftUI text view. This technique can make your app more vibrant and visually appealing, draw attention to specific sections of text, or convey different semantic meanings.

Basics: How to Set Text Color

In SwiftUI, setting a color for a text view is achieved using the .foregroundColor() modifier:

Text("Hello, SwiftUI!")

In this example, “Hello, SwiftUI!” will be displayed in blue color.

Create Multi-colored Text

To use different colors for different parts of a text view in SwiftUI, you’ll need to combine multiple text views, each with its own color:

Text("Hello, ")
    + Text("SwiftUI!")

In this example, “Hello, ” is displayed in red, and “SwiftUI!” is in green.

Multicolor text in swiftui

Utilizing Color for Semantic Meaning

Colors can also be used to convey semantic meaning or state. For example, red is often associated with error messages or alerts, while green signifies success:

Text("Success: ")
    + Text("Your transaction was completed.")

Here, “Success: ” is displayed in green, indicating a successful operation, while the remainder of the message is in black.

SwiftUI multicolor text

Utilizing multiple colors in a single SwiftUI text view is a simple yet effective way to add a splash of visual diversity to your app and enhance the user interface. Whether it’s to draw focus to specific text or convey semantic meaning, multicolored text can significantly improve your app’s visual appeal and usability.

Similar Posts

Leave a Reply