2016-07-20 73 views
1

我很難嘗試暫停並從任何UIView旋轉技術的旋轉當前狀態繼續。無限旋轉UIView並暫停/停止動畫,保持狀態,並繼續從當前狀態旋轉

嘗試:

CGAffineTransformRotate 
CGAffineTransformMakeRotation 
CATransform3DMakeRotation 
CABasicAnimation 

基本上,如果我叫view.layer.removeAllAnimations()layer.speed = 0,他們都重置當前旋轉度。

此外,還試圖快照視圖使用圖像,而不是真正的旋轉,但沒有運氣,因爲快照忽略旋轉。

回答

6

終於得償所願,與一個以上的答案上如此,許多在Objective-C,把它們放在一起在UIView的擴展,並將其記錄:

extension UIView { 

     /** 
     Will rotate `self` for ever. 

     - Parameter duration: The duration in seconds of a complete rotation (360º). 
     - Parameter clockwise: If false, will rotate counter-clockwise. 
     */ 
     func startRotating(duration duration: Double, clockwise: Bool) { 
      let kAnimationKey = "rotation" 
      var currentState = CGFloat(0) 

      // Get current state 
      if let presentationLayer = layer.presentationLayer(), zValue = presentationLayer.valueForKeyPath("transform.rotation.z"){ 
       currentState = CGFloat(zValue.floatValue) 
      } 

      if self.layer.animationForKey(kAnimationKey) == nil { 
       let animate = CABasicAnimation(keyPath: "transform.rotation") 
       animate.duration = duration 
       animate.repeatCount = Float.infinity 
       animate.fromValue = currentState //Should the value be nil, will start from 0 a.k.a. "the beginning". 
       animate.byValue = clockwise ? Float(M_PI * 2.0) : -Float(M_PI * 2.0) 
       self.layer.addAnimation(animate, forKey: kAnimationKey) 
      } 
     } 

     /// Will stop a `startRotating(duration: _, clockwise: _)` instance. 
     func stopRotating() { 
      let kAnimationKey = "rotation" 
      var currentState = CGFloat(0) 

      // Get current state 
      if let presentationLayer = layer.presentationLayer(), zValue = presentationLayer.valueForKeyPath("transform.rotation.z"){ 
       currentState = CGFloat(zValue.floatValue) 
      } 

      if self.layer.animationForKey(kAnimationKey) != nil { 
       self.layer.removeAnimationForKey(kAnimationKey) 
      } 

      // Leave self as it was when stopped. 
      layer.transform = CATransform3DMakeRotation(currentState, 0, 0, 1) 
     } 

    } 

使用它像yourView.startRotating(duration: 1, clockwise: true),後來停止做yourView.stopRotating()