2016-12-14 7 views
0

ButtonJitterというクラスを作成しました。コレクションビューのセル内のボタンにアニメーションを追加する

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セル内のボタンをタップすると、これらの関数の1つを呼び出したいと思います。ボタンのクラスも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

私があなただったら、送信者がクラスButttonJitterであるかどうかを確認するためにguard letステートメントを使用し、コンパイラにそのように考えるようにします。このように:

@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オリジナルの関数では、ButtonJitterであってもボタンはUIButtonと見なされます。 UIButtonにはジッタ機能はありません。しかし、あなたが安全に(したがってガードが)あなたのButtonJitterクラスにキャストするなら、ジッタが戻ってくるよりも:-) – ElFitz

関連する問題