2015-02-17 70 views
3

我在創造一個非常簡單的方形按鈕具有以下行爲的煩惱:取消UIControl animateWithDuration開始一個新的動畫

  • 當我把我的手指上的按鈕,應該縮小了一點(動畫)

  • 當我將手指放在按鈕上時,按鈕應該保持在小的狀態。

  • 當我擡起手指時,按鈕應該變回初始大小(動畫)。

問題是,當我在觸摸/舉起動畫播放時,按鈕應停止當前動畫並縮小/增大。現在我只能在完成播放/縮小動畫之後才能與按鈕進行交互。

我試圖在觸摸功能中使用layer.removeAllAnimations()函數...沒有成功。我試圖爲視圖本身和圖層設置動畫。

這是我用來構建自定義按鈕的UIControl的嘗試。

import UIKit 

class TriggerPad: UIControl { 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override init(frame: CGRect) { 
     // I init the Frame with w:200 h:100 in my ViewController 
     super.init(frame: frame) 

     self.backgroundColor = UIColor.clearColor() 

     self.layer.frame = frame 
     self.layer.backgroundColor = UIColor.blueColor().CGColor 
     self.multipleTouchEnabled = true 
    } 

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 

     let oldFrame = self.layer.frame 
     self.layer.removeAllAnimations() 

     UIView.animateWithDuration(2) {() -> Void in 
      self.layer.frame.size.height = 50 
      self.layer.frame.size.width = 100 
      // I need to adjust the origin here 
     } 
    } 

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 

     let oldFrame = self.layer.frame 
     self.layer.removeAllAnimations() 

     UIView.animateWithDuration(2) {() -> Void in 
      self.layer.frame.size.height = 100 
      self.layer.frame.size.width = 200 
      // I need to adjust the origin here 
     } 
    } 
} 
+0

附加信息。它應該像iPhone App Keezy中的Pads一樣工作。 – 2015-02-17 22:19:24

回答

4

你可以解決它添加到UIView的動畫選項.AllowUserInteraction。您的代碼將是:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {() -> Void in 
     self.layer.frame.size.height = 50 
     self.layer.frame.size.width = 100 
     // I need to adjust the origin here 
    }, completion: nil) 
} 

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {() -> Void in 
     self.layer.frame.size.height = 100 
     self.layer.frame.size.width = 200 
     // I need to adjust the origin here 
    }, completion: nil) 
} 

但我認爲你可以到App類似的效果你提及:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {() -> Void in 
     self.transform = CGAffineTransformMakeScale(0.6, 0.6) 
    }, completion: nil) 

} 

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: {() -> Void in 
     self.transform = CGAffineTransformIdentity 
    }, completion: nil) 

} 

因爲這樣一來它使視圖的中心。