Question

I have two labels in my app which purely contain URLs:

-(void)openURLA{
    NSString *url = @"http://urla.com";
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:url]];
}
-(void)openURLB{
    NSString *url = @"http://urlb.com";
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:url]];
}

And this code inside an existing method:

UITapGestureRecognizer *gra = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLA)];
UITapGestureRecognizer *grb = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLB)];

When a user taps on one of these labels, the openURL methods run fine and the URL opens in safari.

I was wondering how I could create just one method that will open the URL and pass an argument containing label1.text or label2.text values?

I am not 100% sure where to begin doing this so I will appreciate some help.

Was it helpful?

Solution

EDITED:

Follow this whole code:

UILabel  * label1 = [[UILabel alloc] initWithFrame:CGRectMake(40, 70, 300, 50)];
    label1.backgroundColor = [UIColor redColor];
    label1.userInteractionEnabled = YES;
    label1.textColor=[UIColor whiteColor];
    label1.text = @"http://urla.com";
    [self.view addSubview:label1];

    UILabel  * label2 = [[UILabel alloc] initWithFrame:CGRectMake(40, 130, 300, 50)];
    label2.backgroundColor = [UIColor redColor];
    label2.userInteractionEnabled = YES;
    label2.textColor=[UIColor whiteColor];
    label2.text =  @"http://urlb.com";
    [self.view addSubview:label2];


    UITapGestureRecognizer *gsture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLS:)];
    [label1 addGestureRecognizer:gsture1];

    UITapGestureRecognizer *gesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLS:)];
    [label2 addGestureRecognizer:gesture2];

And call method of UITapGestureRecognizer

- (void)openURLS:(UITapGestureRecognizer*)gesture
{
    UILabel *lblUrl=(UILabel *)[gesture view];
    NSLog(@"%@", lblUrl.text); // here you get your selected label text.
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:lblUrl.text]];
}

OTHER TIPS

On creating a label set tag like:

    label1.tag = 1000;
    label2.tag = 1001;
 UITapGestureRecognizer *gsture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLS:)];
    [label1 addGestureRecognizer:gsture1];

    UITapGestureRecognizer *gesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLS:)];
    [label2 addGestureRecognizer:gesture2];

and use the following code to find the view it was tapped

- (void)openURLS:(UITapGestureRecognizer*)sender
{
UIView *view = sender.view;
int tag = view.tag;

if (tag == 1000) {
...
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top