前言ide
UIView 不像 UIButton 加了點擊事件就會有點擊效果,體驗要差很多,這裏分別經過自定義和擴展來實現相似 UIButton 的效果。ui
聲明
歡迎轉載,但請保留文章原始出處:)
博客園:http://www.cnblogs.com
農民伯伯: http://over140.cnblogs.comspa
正文code
1、爲 UIView 添加點擊事件blog
extension UIView { func addOnClickListener(target: AnyObject, action: Selector) { let gr = UITapGestureRecognizer(target: target, action: action) gr.numberOfTapsRequired = 1 userInteractionEnabled = true addGestureRecognizer(gr) } }
2、爲 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 能夠換成點擊變動透明度。get