How to make UIView clickable
Solution 1
-(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.
Solution 2
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
:
Listing out the steps from the above link here:
- Drag a Tap Gesture Recognizer object from the
Object library
to your scene, and place it on top of the UIView. - 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. - 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.
- You're done! :D
Solution 3
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")
}
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
ADO.NET, MS SQL SERVER, Windows Forms Applications(VB and C#), Visual FoxPro, ASP.NET, WCF Web Services, Windows Mobile, and Android 2.2 & 3.0. When you sort all of Stackoverflow's members alphabetically, I am last. Check out my Android calculator. It can perform calculations in any numeral system from base 2 to base 36. It is free.Any Base Calculator Add me on google plus and I will add you into my developers circle.
Updated on June 22, 2020Comments
-
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz almost 4 years
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.
-
Ansshkki over 3 yearsFor
clickView
method, add@objc
to expose this instance method to Objective-C