2016-12-14 93 views
0

我創建了一個名爲ButtonJitter的類。將動畫添加到collectionview單元格內的按鈕

class ButtonJitter: UIButton 
{ 

    func jitter() 
    { 
     let animation = CABasicAnimation(keyPath: "position") 
     animation.duration = 0.05 
     animation.repeatCount = 6 
     animation.autoreverses = true 
     animation.fromValue = NSValue(cgPoint: CGPoint.init(x: self.center.x - 7.0, y: self.center.y)) 
     animation.toValue = NSValue(cgPoint: CGPoint.init(x: self.center.x, y: self.center.y)) 
     layer.add(animation, forKey: "position") 
    } 

    func jitterLong() 
    { 
     let animation = CABasicAnimation(keyPath: "position") 
     animation.duration = 0.05 
     animation.repeatCount = 10 
     animation.autoreverses = true 
     animation.fromValue = NSValue(cgPoint: CGPoint.init(x: self.center.x - 10.0, y: self.center.y)) 
     animation.toValue = NSValue(cgPoint: CGPoint.init(x: self.center.x, y: self.center.y)) 
     layer.add(animation, forKey: "position") 
    } 

} 

現在我想在用戶點擊一個collectionview單元格內的按鈕時調用其中的一個函數。我也將按鈕的類設置爲ButtonJitter。此外,我爲該按鈕創建了一個操作。但是我不能在這個動作中調用任何這些函數。

@IBAction func soundBtnPressed(_ sender: UIButton) { 
     if let url = Bundle.main.url(forResource: soundArrayPets[sender.tag], withExtension: "mp3") 
     { 
      player.removeAllItems() 
      player.insert(AVPlayerItem(url: url), after: nil) 
      player.play() 
     } 
    } 

所以我的問題是如何訪問我的動畫功能,所以當用戶點擊我的集合視圖中的按鈕動畫?或者我應該在我的cellForItem atIndexPath方法中調用它們?謝謝

回答

1

如果我是你,我只需使用guard let語句來檢查我的發件人是否是ButttonJitter類,並讓編譯器認爲它是這樣。像這樣:

@IBAction func soundBtnPressed(_ sender: UIButton) { 
    guard let jitterButton = sender as? ButtonJitter else { 
     return 
    } 
    // Now, if the sender is a button of class ButtonJitter, you have a button that is of that class: jitterButton. Do whatever you want with it. Like call jitterButton.jitter() 
    if let url = Bundle.main.url(forResource: soundArrayPets[sender.tag], withExtension: "mp3") 
    { 
     player.removeAllItems() 
     player.insert(AVPlayerItem(url: url), after: nil) 
     player.play() 
    } 
} 
+0

謝謝!這工作,但我不知道你在這裏做了什麼:) –

+0

@Volkan在你的原始功能,你的按鈕被認爲是UIButton,即使它是一個ButtonJitter。而UIButton沒有抖動功能。但是,如果你安全地(因此後衛讓它)將它投到你的ButtonJitter類中,那麼你就會感到不安:-) – ElFitz

相關問題