Search code examples
swiftloopsviewdidload

Use stride to rotate object


I want to use the stride syntax to rotate a object in stride. The box should go through 3 iterations and rotate 270 degrees. I don’t believe everything some of my code below matches the Syntax by word. Just a FYI.

Var box = UIView()

Override func viewdidload(){
Super.viewdidload()

For rotate in Stride(from : 0, to: 3, by +1 ) {

box.transform = box.transform.rotatedby( .pi/2)
}}

Swift, Stirde, loop, viewdidload


Solution

  • you cannot use a loop to do that, because the UI will only be updated after the loop finish

    you can use UIView.animate to do animation and do recursive to achieve n-times animation

    func rotateBox(count: Int) {
            if count > 0 {
                UIView.animate(withDuration: 1, animations: {
                    self.box.transform = self.box.transform.rotated(by: .pi/2)
                }, completion: { _ in
                    self.rotateBox(count: count - 1)
                })
            }
        }