I need to have working rotation animation and the rectangle on the same relative position after changing orientation. Right now the rectangle starts randomly fly around the screen after change orientation of device.
import SwiftUI
struct ContentView: View {
@State private var isAnimating = false
var animation: Animation {
Animation.linear(duration: 1)
.repeatForever(autoreverses: false)
}
var body: some View {
HStack {
Text("Hello, world!")
.padding()
Spacer()
Rectangle()
.frame(width: 20, height: 20)
.foregroundColor(.red)
.rotationEffect(Angle.degrees(isAnimating ? 360 : 0))
.animation(animation)
.onAppear {
isAnimating = true
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
CodePudding user response:
You just need to join animation with value, like
Rectangle()
.frame(width: 20, height: 20)
.foregroundColor(.red)
.rotationEffect(Angle.degrees(isAnimating ? 360 : 0))
.animation(animation, value: isAnimating) // << here !!
.onAppear {
isAnimating = true
}