I have this animation code:
struct CheckmarkAnimation: View {
@State private var isAnimating = false
var body: some View {
ZStack {
Circle()
.trim(to: isAnimating ? 1:0)
.stroke(.green, lineWidth: 3)
.frame(width: 100, height: 100)
.animation(.easeInOut(duration: 1), value: isAnimating)
Image(systemName: "checkmark")
.foregroundColor(.green)
.font(.largeTitle)
.scaleEffect(isAnimating ? 1.5 : 0)
.animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
}
.onAppear {
isAnimating.toggle()
}
}
}
I would like this view to disappear after the scaling effect on the checkmark ends. How do I do this?
CodePudding user response:
Here are 2 ways to do it:
Change drawing color to .clear
after 2 seconds
Here’s a way to have it disappear (turn invisible but still take up space). Change the drawing color to .clear
after 2 seconds:
struct CheckmarkAnimation: View {
@State private var isAnimating = false
@State private var color = Color.green
var body: some View {
ZStack {
Circle()
.trim(to: isAnimating ? 1:0)
.stroke(color, lineWidth: 3)
.frame(width: 100, height: 100)
.animation(.easeInOut(duration: 1), value: isAnimating)
Image(systemName: "checkmark")
.foregroundColor(color)
.font(.largeTitle)
.scaleEffect(isAnimating ? 1.5 : 0.001)
.animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
}
.onAppear {
isAnimating.toggle()
withAnimation(.linear(duration: 0.01).delay(2)) {
color = .clear
}
}
}
}
Use .scaleEffect()
on ZStack
Insert this scale animation before the .onAppear
:
.scaleEffect(isAnimating ? 0.001 : 1)
.animation(.linear(duration: 0.01).delay(2), value: isAnimating)
.onAppear {
isAnimating.toggle()
}
Note: Use 0.001
instead of 0
in scaleEffect
to avoid
ignoring singular matrix: ProjectionTransform
messages in the console.
CodePudding user response:
.scaleEffect() on ZStack is an elegant solution.
struct CheckmarkAnimation: View {
@State private var isAnimating = false
@State private var color = Color.green
var body: some View {
ZStack {
Circle()
.trim(to: isAnimating ? 1:0)
.stroke(color, lineWidth: 3)
.frame(width: 100, height: 100)
.animation(.easeInOut(duration: 1), value: isAnimating)
Image(systemName: "checkmark")
.foregroundColor(color)
.font(.largeTitle)
.scaleEffect(isAnimating ? 1.5 : 0)
.animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
}
.scaleEffect(isAnimating ? 0 : 1)
.animation(.linear(duration: 0.01).delay(2), value: isAnimating)
.onAppear {
isAnimating.toggle()
}
}
}
This code works and makes the view disappear^^