Tuesday, January 12, 2016

Objective C touch events on UILabel and UIImageView and UIView

We all know that for touch events we have so many interactive UI controls like UIButton that UIKit provides. But what If we want to add interactions on controls like UILabel, UIView etc... 

These are static controls. That means these are given in the UIKit just only for the viewing purpose. Like UILabel to display static text and UIImagesView to display static images.


Let's see how we can add touch actions on these static things which doesn't have any touch events in built.



                         


Here comes gesture recognizers into picture. We can use UITapGestureRecognizer to add tap events on these static controls.

Let's say we have a label called myLabel. I want something to be happened when user taps on it.

UILabel *myLabel = [UILabel alloc] init];

Here I am initializing a UITapGestureRecognizer and adding it to my label.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTapped:)];
[myLabel addGestureRecognizer:tapGesture];

Now, whenever user taps on this label a method named labelTapped will get called.

After checking this, Please don't come back here and scold me :)

We are not yet done with touch action on this label. We forgot the main thing here to complete this tap action. As I have said earlier, these are static controls and by default the user interaction for these controls is disabled. We need to explicitly enable user interaction for these static controls to make tap action work.

[myLabel setUserInteractionEnabled:YES];

We are done now. Add this interaction enabling. Your label starts taking user interactions.

Same piece of code works for UIImageView and UIView.


Hope this post is helpful. Feel free to comment in case of any queries.