【Swift 2.1】為 UIView 添加點擊事件和點擊效果


 

前言

  UIView 不像 UIButton 加了點擊事件就會有點擊效果,體驗要差不少,這里分別通過自定義和擴展來實現類似 UIButton 的效果。

 

聲明
  歡迎轉載,但請保留文章原始出處:)
  博客園:http://www.cnblogs.com
  農民伯伯: http://over140.cnblogs.com

 

正文

  一、為 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 可以換成點擊變更透明度。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM