— SwiftUI, iOS, Animation — 1 min read
symbolEffect
is a new modifier in SwiftUI that allows you to apply animations to system icons. This can be useful for adding visual feedback to user interactions, or for creating more engaging UIs. Keep in mind that this is an iOS 17 feature so you will need to be targeting iOS 17 to use it.
The basic usage of symbolEffect
is to apply a single animation to an icon. Here's an example:
1struct AnimationView3: View {2 @State private var isAnimating = false3 4 var body: some View {5 Button {6 isAnimating.toggle()7 } label: {8 Image(systemName: "heart.fill")9 .symbolEffect(.bounce, value: isAnimating)10 }11 }12}
In this example, the bounce
effect is applied to the heart icon. When the button is tapped, the isAnimating
state variable is toggled, which causes the icon to bounce.
You can customize the animation applied by symbolEffect
by passing in options. Here's an example:
1struct AnimationView3: View {2 @State private var isAnimating = false3 4 var body: some View {5 Button {6 isAnimating.toggle()7 } label: {8 Label("Heart", systemImage: "heart.fill")9 .symbolEffect(.pulse, options: .speed(2).repeat(2), value: isAnimating)10 }11 }12}
In this example, the pulse
effect is applied to the heart icon, with a speed of 2 and a repeat count of 2. When the button is tapped, the isAnimating
state variable is toggled, which causes the icon to pulse twice as fast as the default speed(the default multiplier is 1.0), and will repeat twice.
You can also use symbolEffect
with state to create more dynamic animations. Here's an example of a simple counter View that implements symbolEffect:
1struct ContentView: View {2 @State private var count = 13 4 var body: some View {5 VStack(spacing: 30) {6 Text("Count: \(count)")7
8 Button {9 count += 110 } label: {11 Image(systemName: "plus")12 .symbolEffect(.pulse, value: count)13 }14 }15 }16}
When the user presses the Button the Image inside will animate in a pulsing fashion!