1

更改方向后,我需要在相同的相对位置上有工作的旋转动画和矩形。现在,在更改设备方向后,矩形开始在屏幕上随机飞行。

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()
    }
}
4

1 回答 1

1

你只需要加入具有价值的动画,比如

Rectangle()
    .frame(width: 20, height: 20)
    .foregroundColor(.red)
    .rotationEffect(Angle.degrees(isAnimating ? 360 : 0))
    .animation(animation, value: isAnimating)             // << here !!
    .onAppear {
        isAnimating = true
    }
于 2021-11-05T17:13:48.257 回答