Hi,
We all know that buttons has their own IBActions that can be drawn easily via xibs/storyboard and codes. But what if the view type is UIImageView or UILabel or any other.
In that case we can use UITapGestureRecognizer which is a concrete subclass of UIGestureRecognizer that will do for us.
Following the steps (below) will help you to accomplish or handle actions when an UIImageView or UILabel is tapped.
1- Create an instance of UITapGestureRecognizer with target and action.
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.gestureCalled(gesture:)))
you have to defined an action gestureCalled somewhere in target class.
func gestureCalled(gesture:UITapGestureRecognizer) -> Void {
// handle tap gesture
}
Once you are done with tap gesture you can give it’s number of types, although it’s 1 by default.
tapGesture.numberOfTapsRequired = 1
2- Now add above created instance to UIImageView object.
imageView.addGestureRecognizer(tapGesture)
3- Most of us usually forget to make user interaction enabled for the view to which we are assigning the UITapGesture. So please don’t forget otherwise you won’t be able to get the click event. So let's enable user interaction.
imageView.isUserInteractionEnabled = true
That’s all and you’re done.
Now run your code, you can see that you’ll be able to handle click event for your UIImageView. :)
Thank You
0 Comment(s)