I created a sub class for a UIButton so I could get an animation effect on tap, the effect works, what doesn't work is when I try took hook it up to a @IBAction in my view controller. The function isn't getting called. I have the sub class set as the buttons class in my scoreboard. Here's my code:
import UIKit
class SpringyButton: UIButton {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1)
}, completion: nil)
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.9, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
self.layer.transform = CATransform3DMakeScale(1, 1, 1)
}, completion: nil)
}
}
and my IBAction in my ViewController:
@IBAction func test(sender: AnyObject) {
println("go")
}
I'm not sure what's causing this, any ideas?
Side Note: I've read that subclassing a UIButton isn't such a great idea, would it be better to subclass UIView and hook that up with a tap gesture recognizer?
Thanks.
I believe that Interface Builder only uses UIButton. So subclassing won't really work. If you really want to use your custom class, you can programmatically create it.
Let me know if that works and/or if that's what you were looking for!
The problem is that you just override the touch events. You have to call super after overriding the function. For example in the
touchesBegan
function below:like this you have to add super to all of your touch events that you override. If you encounter any problem please let me know.