m34
m34

Reputation: 35

Can uilabel executes action

In Instagram in the header view we could see there is the profile image and the username right , so I am thinking how is this possible because the username is a UILabel how when it's clicked on it sent you the user homepage . Any idea ?

Upvotes: 2

Views: 73

Answers (2)

Saheb Roy
Saheb Roy

Reputation: 5957

Yes it can, check "User Interaction Enabled" in the Attribute Inspector, and add an Action method with it. Make sure you connect the action method to the label

EDIT-

I am showing this in code as i cant post screenshots.

Create a Label @property(nonatomic, weak) IBOutlet UILabel *myLabel;

Connect the Label in Storyboard.

Create a method, that you want to do when user Taps the label.

-(void)showHello{
    NSLog(@"Hello World");
}

Now declare a

UITapGestureRecognizer *tap; 

I used tapGesture as I want the action to run when I TAP the label.Declare this Gesture as an Instance Variable

in viewDidLoad alloc and init the gesture and add it to the Label

  - (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.myLabel.userInteractionEnabled = YES;
    tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showHello)];
    [self.myLabel addGestureRecognizer:tap];  
}

Yup that should do it

Upvotes: 1

Anil Varghese
Anil Varghese

Reputation: 42977

You can add a UITapGestureRecognizer to the label to make it clickable.

UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedOnLabel:)];
[label setUserInteractionEnabled:YES];
[label addGestureRecognizer:gesture];


-(void)tappedOnLabel:(UIGestureRecognizer*)gestureRecognizer
{
   // Perform your action
}

Upvotes: 2

Related Questions