How to set a variable color to the SFSymbol in SwiftUI

With SFSymbols 4 Apple introduced symbols that have variable color. SFSymbols are built with layers. Variable color is a fraction value between 0 and 1 that allows us to turn on and off those layers, and display a symbol in different states.

For example the wifi symbol with variable color set to 0 represents the "no signal" state. But if we set the variable color to 1 we will get the "full strength" state:

HStack(spacing: 32) {
	Image(systemName: "wifi", variableValue: 0.0)
	Image(systemName: "wifi", variableValue: 0.5)
	Image(systemName: "wifi", variableValue: 1.0)
}

We can also change the variable color dynamically:

struct Content: View {
    @State var variableValue: Double = 0
    
    var body: some View {
        VStack(spacing: 32) {
            HStack(spacing: 32) {
                Image(systemName: "slowmo", variableValue: variableValue)
                Image(systemName: "speaker.wave.3.fill", variableValue: variableValue)
                Image(systemName: "ellipsis.message.fill", variableValue: variableValue)
                Image(systemName: "wifi", variableValue: variableValue)
                Image(systemName: "chart.bar.fill", variableValue: variableValue)
                Image(systemName: "touchid", variableValue: variableValue)
            }
            .foregroundStyle(.green)
            .symbolRenderingMode(.multicolor)
            .font(.system(size: 50))
            
            Slider(value: $variableValue)
                .padding(.all)
        }
    }
}

That's it. If you want to know more details about SFSymbol variable color I recommend watching Adopt Variable Color in SF Symbols video from WWDC 2022.


Comments

Anything interesting to share? Write a comment.