How can I fix a memory leak which happens when I use compound modifiers with an animation?
In this example we have 4 MySquareView
squares that have an animated rotation effect, and these sit within a ZStack in ContentView
which has a scale modifier. As you can see the memory in use continues to increase over time.
The same issue seems to happen with other modifiers too. Full example:
import SwiftUI
struct MySquare: Identifiable, Hashable {
var id = UUID()
var offsetX: CGFloat
var offsetY: CGFloat
}
struct MySquareView: View {
@State private var rotateSquare = true
var body: some View {
Rectangle()
.fill(Color.purple)
.frame(width: 30, height: 30)
.rotationEffect(.degrees(self.rotateSquare ? -25 : 25))
.onAppear(perform: {
withAnimation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true)) {
self.rotateSquare.toggle()
}
})
}
}
struct ContentView: View {
var mySquares = [
MySquare(offsetX: -40, offsetY: 40),
MySquare(offsetX: 50, offsetY: -20),
MySquare(offsetX: -10, offsetY: 80),
MySquare(offsetX: 110, offsetY: 20)
]
var body: some View {
VStack {
ZStack {
ForEach(mySquares, id: \.self) { mySquare in
MySquareView()
.offset(x: mySquare.offsetX, y: mySquare.offsetY)
}
}
.scaleEffect(0.8)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}