Rotate a view for 360 degrees indefinitely in Swift?

后端 未结 10 1197
闹比i
闹比i 2020-12-05 13:06

I want to rotate an image view for 360 degrees indefinitely.

UIView.animate(withDuration: 2, delay: 0, options: [.repeat], animations: {
    self.view.transf         


        
10条回答
  •  一向
    一向 (楼主)
    2020-12-05 13:53

    I think what you really want here is to use a CADisplayLink. Reason being that this would be indefinitely smooth versus using completion blocks which may cause slight hiccups and are not as easily cancelable. See the following solution:

    var displayLink : CADisplayLink?
    var targetView = UIView()
    
    func beginRotation () {
    
        // Setup display link
        self.displayLink = CADisplayLink(target: self, selector: #selector(onFrameInterval(displayLink:)))
        self.displayLink?.preferredFramesPerSecond = 60
        self.displayLink?.add(to: .current, forMode: RunLoop.Mode.default)
    }
    
    func stopRotation () {
    
        // Invalidate display link
        self.displayLink?.invalidate()
        self.displayLink = nil
    }
    
    // Called everytime the display is refreshed
    @objc func onFrameInterval (displayLink: CADisplayLink) {
    
        // Get frames per second
        let framesPerSecond = Double(displayLink.preferredFramesPerSecond)
    
        // Based on fps, calculate how much target view should spin each interval
        let rotationsPerSecond = Double(3)
        let anglePerSecond = rotationsPerSecond * (2 * Double.pi)
        let anglePerInterval = CGFloat(anglePerSecond / framesPerSecond)
    
        // Rotate target view to match the current angle of the interval
        self.targetView.layer.transform = CATransform3DRotate(self.targetView.layer.transform, anglePerInterval, 0, 0, 1)
    
    }
    

提交回复
热议问题