This is a Apple Watch Project.
Am trying to animate a Heart shape such that it shows up as Pulsing (via scaleEffect
when workout is started / receiving HR.
Below is a Minimally Reproducible Example of what I have tried (among a few solutions). I am only able to get the animation to stop using the 2nd method which has the .default
animation style
While it works, Would like to understand why the 1st method doesn't work. (Spent hours figuring this out)
//
// HRView.swift
// MyWorkouts WatchKit Extension
// https://stackoverflow.com/questions/66603212/swiftui-text-unexpected-padding-bottom-and-top
// https://stackoverflow.com/a/67880356/14414215 - Animate HR
// https://stackoverflow.com/questions/69443588/how-to-replace-deprecated-animation-in-swiftui
// https://stackoverflow.com/a/65433966/14414215
// https://stackoverflow.com/a/61972436/14414215
import SwiftUI
import WatchKit
import HealthKit
struct HRView: View {
@State var animateHr = false
@State private var animationAmount: CGFloat = 0
var body: some View {
VStack (alignment: .center, spacing: 0) {
HStack {
// This will stop the animation
Image(systemName: "heart.fill")
.resizable()
.frame(width: 30, height: 30)
.padding(20)
.foregroundColor(.red)
.scaleEffect(1 + self.animationAmount)
.animation(animateHr ? Animation.linear(duration: 0.1).delay(0.3).repeatForever(autoreverses: true) : .default, value: 1 + self.animationAmount)
Spacer()
// This doesn't stop - 2nd Method
// https://stackoverflow.com/a/59829109/14414215
Image(systemName: "heart.fill")
.resizable()
.frame(width: 30, height: 30)
.padding(20)
.foregroundColor(.blue)
.scaleEffect(1 + self.animationAmount)
.animation(.linear(duration: 0.1).delay(0.3).repeatForever(autoreverses: true), value: 1 + self.animationAmount)
}
Spacer()
Text("122")
.font(.system(size: 110))
.padding(.vertical,-90 * 0.23)
Spacer()
HStack(alignment: .bottom) {
Button {
self.animateHr.toggle()
self.animationAmount = self.animateHr ? 0.2 : 0
let _ = print("Button Pressed animateHr:\(self.animateHr) animationAmount:\(self.animationAmount)")
} label: {
Text(self.animateHr ? "END" : "START")
.foregroundColor(.white)
.frame(width: 100, height: 20)
.background(RoundedRectangle(cornerRadius: 8)
.fill(Color.red))
}
.font(.system(size: 15))
.buttonStyle(PlainButtonStyle())
}
}
.edgesIgnoringSafeArea(.bottom)
.onAppear {
}
}
}
struct HRView_Previews: PreviewProvider {
static var previews: some View {
HRView()
}
}
Xcode 14, iOS16, WatchOS8 (All done in the simulator)