Change the label color of a SwiftUI Toggle switch
In this tutorial, we will see how to change the color of the label of a toggle switch in SwiftUI.
We can simply change the label color of a TextField by applying the .foregroundColor() modifier and specifying our preferred color within this modifier.
Syntex
.foregroundColor(.red)
If we apply the above code to a Toggle, it will change the label color of the toggle to red.
Change the color of label
First of all, I will create a simple toggle switch using the Toggle , and apply the foregroundColor() modifier to the Toggle and specify the color within this modifier to change the label color.
Example
Toggle("Toggle Switch", isOn: $isToggled)
//To change the label color
.foregroundColor(.red)In the above code, I have applied the foregroundColor() modifier to the Toggle by specifying the color .red. So, it will display the label text “Toggle Switch” in red color.
Output:

Change the label color conditionally
We can also change the label color of a toggle conditionally using the foregroundColor() modifier. We can pass conditions within this modifier.
Example
import SwiftUI
struct ContentView: View {
@State private var isToggled = false
var body: some View {
Toggle("Toggle Switch", isOn: $isToggled)
.foregroundColor(isToggled ? Color.mint : Color.red)
.font(.title)
.padding()
}
}In the above code, I have passed a condition within the foregroundColor() modifier and applied it to the Toogle.
Here, the condition is, if we enable the toggle the isToggle state will be true so it will change the label color to mint. Otherwise, it will be red.
Output:

Leave a Reply