Dynamically adjust the color of an SF Symbol in SwiftUI

In this tutorial, we will see how to dynamically adjust the color of an SF Symbol in SwiftUI.

We can use SF Symbol to display icons in our app in SwiftUI. SF Symbols are a set of icons provided by Apple.

Fill different parts of the symbol

Imagine we have a Wi-Fi icon, and we want to show a part of it filled based on a fraction, let’s say 0.5 (half-filled).

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        // To display an Image view with the system icon named "wifi"
        Image(systemName: "wifi", variableValue: 0.5)
            // To set the font size of the image
            .font(.system(size: 80))
            // To set a foreground color style to the image
            .foregroundStyle(.mint)
    }
}

Output:

Fill different parts of the symbol

Dynamically fill the different part

We can also fill the different parts of an SF Symol dynamically using a Slider and defining a @State property wrapper.

Example:

import SwiftUI

struct ContentView: View {
    // State variable to control the value for the Slider
    @State private var value = 0.5
    
    var body: some View {
        VStack {
            Image(systemName: "wifi", variableValue: value)
                .font(.system(size: 80))
                .foregroundStyle(.mint)
            // Slider view bound to the 'value' state variable
            Slider(value: $value)
        }
        .padding()
    }
}

In the above program, the @State property wrapper is used to create a mutable state variable named value, which is set to 0.5.

Then, the Slider view is bound to this value variable using $value, which means the slider reflects the changes made to value.

Output:

Dynamically fill the different part

Dynamically change the color of an SF Symbol

We can also dynamically change the color of the SF Symbol inside the Image view using the foregroundStyle() modifier and binding it to the slider’s value.

Example

import SwiftUI

struct ContentView: View {
    @State private var value = 0.5

    var body: some View {
        VStack {
            // Image with SF Symbol whose color changes dynamically
            Image(systemName: "wifi")
                .font(.system(size: 80))
                .foregroundStyle(Color(hue: value, saturation: 1, brightness: 1))
                .padding()

            // Slider view bound to the 'value' state variable
            Slider(value: $value)
        }
        .padding()
    }
}

In the above program, the .foregroundStyle(Color(hue: value, saturation: 1, brightness: 1)) will change the foreground color of the image dynamically based on the value state variable.

It uses the Color initializer with a dynamic hue value determined by the value state variable and a fixed saturation and brightness of 1.

Output:

Dynamically change the color of an SF Symbol

Leave a Reply

Your email address will not be published. Required fields are marked *