How to make UIView clickable

Swift 5.x

let tap = UITapGestureRecognizer(target: self, action: #selector(funcName))  
myView.addGestureRecognizer(tap)

Then put you code inside funcName

@objc func funcName() {
    // Your code goes here..
}

-(void)addGestureRecogniser:(UIView *)touchView{

    UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changecolor)];
    [touchView addGestureRecognizer:singleTap];
    DBLog(@"ADD GESTURE RECOGNIZER");
}
-(void)changecolor{

  // do something


}

1`) this is code snippet where in u need to pass the view as a parameter so as to make it clickable.


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")
}

Another way is to hook up the gesture recognizer via storyboard/ Interface Builder.

It's very easy and, I feel, cleaner than using code.

Here is the step-by-step reference to set up Gesture Recognizer. Just search for Gesture Recognizer:

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html#//apple_ref/doc/uid/TP40015214-CH6-SW1

Listing out the steps from the above link here:

  1. Drag a Tap Gesture Recognizer object from the Object library to your scene, and place it on top of the UIView.
  2. You will see a Tap Gesture Recognizer in the scene dock. The Scene dock is the top of the View Controller in the storyboard where you have First Responder, Exit, etc.
  3. Connect the Tap Gesture Recognizer to your code by Control-dragging from the gesture recognizer in the scene dock to the code display. Fill the Action dialog as you would do for a UIButton action.
  4. You're done! :D