我创建了一个名为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单元格内的按钮时,我想调用其中一个函数。我已将按钮的类设置为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方法中调用它们?感谢
答案 0 :(得分: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()
}
}