Where exactly is the error ? On timer probably.
That's because you declare the function as mutating (as compiler asks for).
But you have then to make timer a State variable:
struct Pos_View: View {
@ObservedObject var element_1 = Element(imageName: "pic_1", name: "", size: CGSize(width: 100, height: 100), position: PositionConstants.pos_1)
let Input_Matrix = Input.input_1
// Index to track current row in matrix
@State var currentIndex = 0
// Timer to trigger updates
@State private var timer: Timer? // <<-- State var
var body: some View {
VStack {
// Display element
Image(element_1.imageName)
.resizable()
.frame(width: element_1.size.width, height: element_1.size.height)
.position(element_1.position)
// Button to start animation
Button("Start Animation") {
startAnimation()
}
}
}
/*mutating*/ func startAnimation() { // <<-- no mutating
currentIndex = 0 // Reset index before starting animation
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {timer in
if self.currentIndex < self.Input_Matrix.count {
let isFirstElementOne = self.Input_Matrix[self.currentIndex][0] == 1
let newPosition = isFirstElementOne ? PositionConstants.pos_2 : PositionConstants.pos_1
withAnimation {
self.element_1.position = newPosition
}
self.currentIndex += 1
} else {
// Stop the timer when we reach the end of matrix
timer.invalidate()
}
}
}
}
Topic:
Programming Languages
SubTopic:
Swift
Tags: