In this tutorial, I am going to let you know about the
colorInvert() modifier in SwiftUI with some examples.
colorInvert() modifier, you can invert all the colors in a view. In this way, each color will be changed into its complementary or opposite color. In a simple example, if the background color or foreground color is black, it will change it to white. This is because the opposite color of black is white.
Let’s see an example of inverting the color of a SwiftUI Text view using the
Text("This is the Text") .foregroundColor(.green) .colorInvert()
You can see that in the above SwiftUI code, we have set the font color of our text to green using the
foregroundColor() modifier. But it will show the text in a color that is given in the figure below:
This is because the color of the text is inverted which makes it the opposite of the color green. This is called the inverted color of green.
In the same way, the
colorInvert() modifier can invert all the other colors for example background color, tint color, border color etc.
Below is another example:
Text("This is the Text with font color and background color") .foregroundColor(.red) .padding() .background(.blue) .colorInvert()
The above program will change both the font color and background color to invert of the provided color.
Now it’s time to apply the
colorInvert() modifier to a different type of view. Actually, we will apply it to a Slider and check how it is going to look like.
In default, a SwiftUI Slider looks like you can see in the image below:
Let’s apply the
colorInvert() to the SwiftUI slider as you can see below:
Slider(value: $sliderVal, in: 0...100, step: 1) .colorInvert()
This time, our slider looks like in the image given below:
Just look at the above image. The colors of the slider have been changed. The changed colors are the opposite or inverted colors of the default slider.
In this tutorial, we have applied the
colorInvert() to Text and Slider in SwiftUI. But you can use it to other views also. You can try the
colorInvert() modifier by yourself to different views and controls. I hope, this article is helpful to you.