2015-02-09 147 views
0

我有一個非常簡單的示例,可以拖動UIView。當觸摸時,我將在拖動方向上產生一個慣性效果。而如果我再次觸碰,我需要停止所有的慣性動畫,並開始做另一次拖動。這裏是我的代碼,「clearAllAnimations」不會停止我的動畫。我怎麼能實現呢?爲什麼「RemoveAllAnimations()」不會停止我的動畫?

import UIKit 

class ViewController: UIViewController { 
    var tile : UIView = UIView() 
    var labelView = UITextView() 
    var displayLink : CADisplayLink? 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tile.frame = CGRect(x: 0, y: 0, width: 256, height: 256) 
     tile.backgroundColor = UIColor.redColor() 
     view.addSubview(tile) 

     var panGesture = UIPanGestureRecognizer(target: self, action: Selector("panHandler:")) 
     view.addGestureRecognizer(panGesture) 

     labelView.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 44) 
     labelView.backgroundColor = UIColor.clearColor() 
     view.addSubview(labelView) 
    } 

    func panHandler (p: UIPanGestureRecognizer!) { 
     var translation = p.translationInView(view) 
     if (p.state == UIGestureRecognizerState.Began) { 
      self.tile.layer.removeAllAnimations() 
     } 
     else if (p.state == UIGestureRecognizerState.Changed) { 
      var offsetX = translation.x 
      var offsetY = translation.y 

      var newLeft = tile.frame.minX + offsetX 
      var newTop = tile.frame.minY + offsetY 

      self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height) 
      labelView.text = "x: \(newLeft); y: \(newTop)" 
      p.setTranslation(CGPoint.zeroPoint, inView: view) 
     } 
     else if (p.state == UIGestureRecognizerState.Ended) { 
      var inertia = p.velocityInView(view) 
      var offsetX = inertia.x * 0.2 
      var offsetY = inertia.y * 0.2 
      var newLeft = tile.frame.minX + offsetX 
      var newTop = tile.frame.minY + offsetY 

      UIView.animateWithDuration(1, delay: 0, options:UIViewAnimationOptions.CurveEaseOut, animations: {_ in 
       self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height) 
       }, completion: nil) 

     } 
    } 
} 

回答

1

設置UIViewAnimationOptions.AllowUserInteraction會訣竅。開始動畫的新代碼是這樣的:

UIView.animateWithDuration(animationDuration, delay: 0, options:UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.BeginFromCurrentState, animations: {_ in 
      self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height) 
      }, completion: nil) 
+0

它不適用於長動畫。 – 2017-09-08 11:45:15