I have a custom UIView that contains a UILabel and a UIImageView. How do I make my UIView clickable? I want the background of the UIView to change any time a user starts to press down on the UIView. The color should change back when the user lifts up on the button. I also need to be able to handle the click event.
The only possible way to add a click event on UIView is using UITapGestureRecognizer . You can either add an UITapGestureRecognizer using interface builder or you can do it programmatically. This way is a bit inefficient as we need to add one function for each view which will be clickable.
Select Touch Up Inside in the event drop-down list. In the Arguments drop-down list, you can select Sender or Sender And Event. Click Connect button, there will add a method in the ViewController source code.
To make UILabel clickable you will need to enable user interaction for it. To enable user interaction for UILabel simply set the isUserInteractionEnabled property to true.
Swift 2.0 Version:
Don't forget to implement UIGestureRecognizerDelegate
// Add tap gesture recognizer to View
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("onClickOnView"))
tapGesture.delegate = self
self.view.addGestureRecognizer(tapGesture)
func onClickOnView(){
print("You clicked on view..")
}
Swift 3.0 Version:
// Add tap gesture recognizer to View
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickView(_:)))
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)
func clickView(_ sender: UIView) {
print("You clicked on view")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With