前言
UIView 不像 UIButton 加了點擊事件就會有點擊效果,體驗要差不少,這裡分別通過自定義和擴展來實現類似 UIButton 的效果。
正文
一、為 UIView 添加點擊事件
extension UIView {
func addOnClickListener(target: AnyObject, action: Selector) {
let gr = UITapGestureRecognizer(target: target, action: action)
gr.numberOfTapsRequired = 1
userInteractionEnabled = true
addGestureRecognizer(gr)
}
}
二、為 UIView 添加點擊效果
class UIViewEffect : UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
backgroundColor = UIColor.groupTableViewBackgroundColor()
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
UIView.animateWithDuration(0.15, animations: { () -> Void in
self.backgroundColor = UIColor.clearColor()
})
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
UIView.animateWithDuration(0.15, animations: { () -> Void in
self.backgroundColor = UIColor.clearColor()
})
}
}
這裡大家可以換成自己的點擊效果,如果是 UIImageView 可以換成點擊變更透明度。