Using a label as a button - when label is touched, assign value to a string

11,645

Looking around, most people recommend using an actual button and setting the background transparent or to the background color.

That said, you can do something like:

In viewWillLoad:

    UILabel * label = [[UILabel alloc] init]; // change/delete to use your obj

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushAction)];
[label addGestureRecognizer:tap];
label.userInteractionEnabled = YES;

then set the selector:

- (void) pushAction
{
    self.myvariable = l1.text;
}
Share:
11,645
user1362308
Author by

user1362308

Updated on June 04, 2022

Comments

  • user1362308
    user1362308 almost 2 years

    I am having some challenges with using a label as a button. I have a label defined as a UILabel, and declared the string variable in my .h file:

    IBOutlet UILabel *l1;
    
    @property(strong)NSString *myvariable;
    

    In the xib, with the label selected, in the Identity Inspector view, under Document, the Label field with the desired label name is set - example: l1. I also have some static text in the label.

    In File's Owner Connection Inspector, I have the l1 Outlet connected to the l1 label.

    My goal: When the label is touched, I would like to simply assign a string variable with a text value such as what might be done in the .m file:

    self.myvariable = l1.text;
    

    Things that I have unsuccessfully tried: - setting up a UIButton in my .h, - tried to set up a UIButton in the .m - in the XIB Identity Inspector view, under Accessibility, tried checking the button Traits checkbox to enable the label as a button

    I haven't figured it out yet. This is probably an easy label question, and most of my experience with labels include static text display, or displaying a countdown based on present date using epoch time. Any guidance would be greatly appreciated!

    Thanks in advance! Rob