Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UIView clickable

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.

like image 292
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz Avatar asked Mar 19 '13 03:03

zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz


People also ask

How to add click to UIView in Swift?

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.

How do I make a button clickable in Swift?

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.

How do you make a UILabel clickable in Swift?

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.


1 Answers

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")
}
like image 85
Phil Avatar answered Oct 05 '22 12:10

Phil