Why does this gradient view crash after some time?

Viewed 37

So I have this custom view I made to make rotating gradient. I do it this way because it's the only way I know how to get the animation I like properly. The issue that after around 10 minutes of using the app or so, it'll crash and I'm not sure why and I do not know how to resolve it.

struct Background: View {
    
    
    
    
    /// Style of gradient animation rotation
    var style: Style = .normal
    @State var start = UnitPoint.leading
    @State var end = UnitPoint.trailing

    var timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()
    
    @State var colors: [Color] = [ .blue, .red ]
    
    
    
  
    
    var body: some View {
        LinearGradient(gradient: Gradient(colors: colors ), startPoint: start, endPoint: end)
            .animation(Animation.easeInOut(duration: 1.5).repeatForever(), value: start) /// don't forget the `value`!
            .onReceive(timer) { _ in
                
                
                self.start = nextPointFrom(self.start)
                self.end = nextPointFrom(self.end)

            }
            .edgesIgnoringSafeArea(.all)
    }
    
    /// cycle to the next point
    func nextPointFrom(_ currentPoint: UnitPoint) -> UnitPoint {
        switch currentPoint {
        case .top:
            return .topTrailing
        case .topLeading:
            return .top
        case .leading:
            return .topLeading
        case .bottomLeading:
            return .leading
        case .bottom:
            return .bottomLeading
        case .bottomTrailing:
            return .bottom
        case .trailing:
            return .bottomTrailing
        case .topTrailing:
            return .trailing
        default:
            print("Unknown point")
            return .top
        }
    }
    
    
}


 

Here is how it may be used


struct ContentView: View {

    var body: some View {

        ZStack {

          Background()
          OtherViews()
}

}


}

Here is the error I get after around 10 minutes of it running but I don't know what it is

enter image description here

1 Answers

By my testing it leaks memory, so this might be a reason, try the following modified part - animation duration set to same as timer interval but removed repeating, because it is anyway restarted on update:

LinearGradient(gradient: Gradient(colors: colors ), startPoint: start, endPoint: end)
    .animation(Animation.easeInOut(duration: 2), value: start) // << here !!
Related