Swift 2.1 adds click events and click effects to UIView

  • 2020-06-15 10:20:55
  • OfStack

preface

Unlike UIButton, UIView does not add click event to get click effect. The experience is much worse.

The body of the

1. Add click events for UIView


extension UIView {

  func addOnClickListener(target: AnyObject, action: Selector) {
    let gr = UITapGestureRecognizer(target: target, action: action)
    gr.numberOfTapsRequired = 1
    userInteractionEnabled = true
    addGestureRecognizer(gr)
  }

}

2. Add click effects to 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()
    })
  }
}

Here you can change it to your own click, if it's UIImageView you can change it to click change transparency.


Related articles: