タップしたかどうかはtouchesBeganなどを使います。
下記はtouchesBeganした時に、
「ボタンがわずかに縮小し、alphaが若干薄くなる」
というUIButtonを継承したクラスを作ってみました。
import UIKit
class UIButtonAnimated: UIButton {
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
self.touchStartAnimation()
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
self.touchEndAnimation()
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
self.touchEndAnimation()
}
private func touchStartAnimation(){
UIView.animateWithDuration(0.1,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseIn,
animations: {() -> Void in
self.transform = CGAffineTransformMakeScale(0.95, 0.95);
self.alpha = 0.7
},
completion: nil
)
}
private func touchEndAnimation(){
UIView.animateWithDuration(0.1,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseIn,
animations: {() -> Void in
self.transform = CGAffineTransformMakeScale(1.0, 1.0);
self.alpha = 1
},
completion: nil
)
}
}
利用するときは普通のUIButtonと同じく
let btn = UIButtonAnimated(frame: CGRectMake(0, 0, 100, 100))
という感じで使えばOKです。