Reputation: 164
I have created a class called 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")
}
}
Now I want to call one of these functions when user taps to a button inside a collectionview cell. I have set the class of the button as ButtonJitter as well. Also I have created an action for that button. But I can't call any of these functions inside of that action.
@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()
}
}
So my question is how can I access my animation functions so when user taps the button inside my collection view it animates? Or should I call them inside my cellForItem atIndexPath method? Thanks
Upvotes: 0
Views: 203
Reputation: 988
If I were you, I'd simply use a guard let statement to check if my sender is of class ButttonJitter, and have the compiler consider it as such. Like this:
@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()
}
}
Upvotes: 1