Search code examples
swiftanimationrotationuiviewpropertyanimator

reverse the rotation of a object


In my swift code func rotate rotates a football. In leftB I want to reverse the rotation of the football. Currently the rotation is going clockwise. If leftB is hit I want the rotation direction to be reversed from the same location.

    func Rotate() {
  
        self.rotation = UIViewPropertyAnimator(duration: 10, curve: .linear, animations: {
            self.football.transform = self.football.transform.rotated(by: CGFloat.pi)
        })

        self.rotation?.addCompletion { [weak self] (_) in
            self?.Rotate()
        }

        self.rotation?.startAnimation()


}


@objc func leftB() {
}

Solution

  • If you use a rotation angle of π, the system can't tell if it's supposed to rotate clockwise or counter-clockwise. That's because rotating by π represents a 180 degree rotation, and you could do that by going clockwise or counter-clockwise. Use rotation changes of π/2 or -π/2.

    Here is some code that works, from a little sample project I slapped together to demonstrate how to make it work:

        enum RotationDirection: Int {
            case clockwise
            case counterclockwise
        }
        
        @IBAction func doRotate(_ sender: UIButton) {
            defer {
                let buttonTitle = isRotating ? "Stop rotating" : "Rotate"
                sender.setTitle(buttonTitle, for: .normal)
            }
            if isRotating  {
                isRotating = false
            } else {
                isRotating = true
                rotate()
            }
        }
        
        func rotate() {
            
            guard isRotating else { return }
            
            let rotationAngle = rotationDirectionControl.selectedSegmentIndex == RotationDirection.clockwise.rawValue ? CGFloat.pi/2 : -CGFloat.pi/2
            self.rotation = UIViewPropertyAnimator(duration: 0.5, curve: .linear, animations: {
                self.football.transform = self.football.transform.rotated(by: rotationAngle)
            })
            
            self.rotation?.addCompletion { [weak self] (_) in
                self?.rotate()
            }
            self.rotation?.startAnimation()
        }
    

    Edit:

    You can download a sample project using the above code here.

    (I animated a UILabel whose outlet I named "football." Yours is probably a UIImage.)