Last active
May 24, 2023 17:47
-
-
Save mattyoung/cbd1e89a01953a3f4cdc5a035cad4806 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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