0
0
Ios-swiftHow-ToBeginner ยท 3 min read

How to Use foregroundColor in SwiftUI: Simple Guide

In SwiftUI, use the foregroundColor modifier to change the color of text, images, or shapes. Apply it directly to a view like Text or Image to set its color, for example: Text("Hello").foregroundColor(.red).
๐Ÿ“

Syntax

The foregroundColor modifier sets the color of the foreground elements like text or icons in a view.

It takes a Color value as its parameter.

Example parts:

  • Text("Hello"): The view to color.
  • .foregroundColor(Color.red): Applies red color to the text.
swift
Text("Hello World").foregroundColor(Color.blue)
Output
The text "Hello World" displayed in blue color.
๐Ÿ’ป

Example

This example shows how to use foregroundColor to change the color of text and an SF Symbol icon.

swift
import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack(spacing: 20) {
      Text("Welcome to SwiftUI")
        .foregroundColor(.green)
        .font(.title)
      Image(systemName: "star.fill")
        .foregroundColor(.yellow)
        .font(.largeTitle)
    }
  }
}
Output
A vertical stack showing green "Welcome to SwiftUI" text and a large yellow filled star icon below it.
โš ๏ธ

Common Pitfalls

Common mistakes when using foregroundColor include:

  • Applying foregroundColor to a container view like VStack expecting all children to inherit the color (they do not inherit automatically).
  • Using colors that do not contrast well with the background, making text hard to read.
  • Forgetting to import SwiftUI or using UIColor instead of Color in SwiftUI views.
swift
/* Wrong: color applied to VStack does not affect children */
VStack {
  Text("Hello")
  Text("World")
}
.foregroundColor(.red) // This does NOT color the texts red

/* Right: apply color to each text */
VStack {
  Text("Hello").foregroundColor(.red)
  Text("World").foregroundColor(.red)
}
Output
First snippet: texts remain default color. Second snippet: both texts appear red.
๐Ÿ“Š

Quick Reference

UsageDescription
Text("Hi").foregroundColor(.blue)Colors text blue
Image(systemName: "heart").foregroundColor(.red)Colors icon red
Shape().foregroundColor(.green)Colors shape green
View.foregroundColor(nil)Resets to default color
โœ…

Key Takeaways

Use foregroundColor to set the color of text, images, and shapes in SwiftUI.
Apply foregroundColor directly to the view you want to color; it does not cascade automatically.
Use SwiftUI's Color type, not UIKit UIColor, for compatibility.
Choose colors with good contrast for readability.
foregroundColor(nil) resets the color to default.