2016-07-20 15 views
1

UIView回転技法の回転の現在の状態から一時停止しようとして苦労しています。UIViewを無期限に回転させ、アニメーションの一時停止/停止、状態の保持、現在の状態からの回転の継続

が試み:

CGAffineTransformRotate 
CGAffineTransformMakeRotation 
CATransform3DMakeRotation 
CABasicAnimation 

基本的に、私はview.layer.removeAllAnimations()や、layer.speed = 0を呼び出す場合、それらはすべて、現在の回転度をリセットします。

また、スナップショットが回転を無視したため、実際の回転の代わりに画像を使用するためのビューのスナップショットを試みましたが、運がありませんでした。

答えて

6

最後にObjective-Cの中に多く、SO上で複数の回答で、それを得た、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)のようにそれを使用しますdo yourView.stopRotating()

関連する問題