动画渐变视图在预览中有效 canvas 但在设备上有奇怪的行为

Animating gradient view works in preview canvas but weird behavior on device

这是我用来创建动画渐变视图的方法


struct AnimatedBackground: View {
   @State var start = UnitPoint.leading
   @State var end = UnitPoint.trailing
   
 
   
   let timer = Timer.publish(every: 1, on: .main, in: .default).autoconnect()
   let colors: [Color] = [ .blue, .red ]
   
   
   var body: some View {
       
       
       LinearGradient(gradient: Gradient(colors: colors), startPoint: start, endPoint: end)
           .animation(Animation.easeInOut(duration: 3).repeatForever())
           .onReceive(timer, perform: { _ in
               
              
   
                self.start = .topLeading
               self.end = .bottomTrailing
               
           
               self.start = .bottom
               self.end = .top
           
            
               self.start = .bottomLeading
               self.end = .topTrailing
               
               
               self.start = .leading
               self.end = .trailing
               
        
               self.start = .topLeading
               self.end =  .bottomTrailing
               
               
               self.start = .top
               self.end = .bottom
               
               
               self.start = .bottomLeading
               self.end = .topTrailing
               
            
               self.start = .leading
               self.end = .trailing
               
            
               
           }).edgesIgnoringSafeArea(.all)
   }
}

当我在 Xcode 上的预览 canvas 中查看它时它工作正常但是当我 运行 它在设备上时不仅渐变没有动画而且 视图本身 在屏幕上和屏幕外移动。

如果您只执行 .animation 而没有提供 value,SwiftUI 将为 一切 设置动画。这包括位置变化,例如当设备从纵向变为横向时。

设置您想要的动画(起点和终点),只需将其中之一传递给 value

.animation(Animation.easeInOut(duration: 3).repeatForever(), value: start)
Before After