У меня происходит следующая волновая анимация, и при нажатии кнопки я анимирую ее силу так, чтобы она выравнивалась с анимацией. Однако, когда я снова нажимаю кнопку, волновая анимация не перезапускается. Как мне заставить его снова запустить анимацию?
struct Wave: Shape {
var strength: Double
var frequency: Double
var phase: Double
var animatableData: AnimatablePair {
get { AnimatablePair(phase, strength) }
set {
self.phase = newValue.first
self.strength = newValue.second
}
}
func path(in rect: CGRect) -> Path {
var path = Path()
let width = Double(rect.width)
let height = Double(rect.height)
let midHeight = height / 2
let wavelength = width / frequency
let firstX = 0.0
let firstRelativeX = firstX / wavelength
let firstSine = sin(firstRelativeX + phase)
let firstY = strength * firstSine + midHeight
path.move(to: CGPoint(x: firstX, y: firstY))
for x in stride(from: 0.0, through: width, by: 1) {
let relativeX = x / wavelength
let sine = sin(relativeX + phase)
let y = strength * sine + midHeight
path.addLine(to: CGPoint(x: x, y: y))
}
return path
}
}
struct WaveView: View {
@Binding var isAnimating: Bool
@State private var phase = 0.0
@State private var waveStrength = 50.0
var body: some View {
VStack {
Wave(strength: waveStrength, frequency: 30, phase: phase)
.stroke(.black, lineWidth: 5)
.onChange(of: isAnimating) { _, newValue in
withAnimation(.easeInOut(duration: 0.5)) {
waveStrength = newValue ? 50.0 : 0.0
}
if newValue {
animateWave()
}
}
.onAppear {
animateWave()
}
}
}
private func animateWave() {
withAnimation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) {
self.phase = .pi * 2
}
}
}
struct WaveContainerView: View {
@State var isAnimating = true
var body: some View {
VStack {
WaveView(isAnimating: $isAnimating)
Button("Animate") {
isAnimating.toggle()
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... in-swiftui