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.
How to make UIView clickable
Asked Answered
Sorry for the noob question, I am new to iOS development. –
Downdraft
i usually do it by Tap gesture to mimic the click able UIView –
Outwards
possible duplicate of How to add a touch event to a UIView? –
Warrick
-(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.
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
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")
}
For
clickView
method, add @objc
to expose this instance method to Objective-C –
Hertz 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..
}
© 2022 - 2024 — McMap. All rights reserved.