Skip to content

Instantly share code, notes, and snippets.

@romyios
Forked from codeactual/SFSymbolImage.swift
Created May 24, 2023 17:47
Show Gist options
  • Save romyios/0b735d3d8a905963728591c442be393b to your computer and use it in GitHub Desktop.
Save romyios/0b735d3d8a905963728591c442be393b to your computer and use it in GitHub Desktop.
//
// SFSymbolImage.swift
// SFSymbolVariableValueAnimationWrong
//
// Created by Matthew Young on 12/22/22.
//
import SwiftUI
struct AnimatableVariableValueModifier: Animatable, ViewModifier {
let systemName: String
var animatableData: Double
init(systemName: String, variableValue: Double) {
self.systemName = systemName
animatableData = variableValue
}
func body(content: Content) -> some View {
Image(systemName: systemName, variableValue: animatableData)
.resizable()
.scaledToFit()
}
}
// Creating an Image of SF Symbol with this wil animate its variableValue progress
// Exactly the same as the Image(systemName:variableValue:)
// but this one animate the variableValue correctly
struct SFSymbolImage: View {
let systemName: String
let variableValue: Double
var body: some View {
Color.clear
.modifier(AnimatableVariableValueModifier(systemName: systemName, variableValue: variableValue))
.animation(.linear.repeatForever(), value: variableValue)
}
}
struct SFSymbolImage_Previews: PreviewProvider {
static var previews: some View {
SFSymbolImage(systemName: "wand.and.rays", variableValue: 0.5)
}
}
// ================================== Demo =================================
struct ContentView: View {
@State private var progress = 0.0
var body: some View {
VStack {
Text("Standard SwiftUI animation technique")
Image(systemName: "wand.and.rays", variableValue: progress)
.resizable()
.scaledToFit()
.foregroundColor(.accentColor)
.animation(.linear.repeatForever(), value: progress)
Text("How it should be, how to do?")
SFSymbolImage(systemName: "wand.and.rays", variableValue: progress)
.foregroundColor(.accentColor)
.animation(.linear.repeatForever(), value: progress)
}
.padding()
.onAppear {
progress = 1
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment