0

我的应用中有两个标签,它们纯粹包含 URL:

-(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]];
}

现有方法中的这段代码:

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

当用户点击这些标签之一时,openURL 方法运行良好,并且 URL 在 safari 中打开。

我想知道如何只创建一个方法来打开 URL 并传递包含 label1.text 或 label2.text 值的参数?

我不是 100% 确定从哪里开始这样做,所以我会很感激一些帮助。

4

2 回答 2

1

编辑:

遵循整个代码:

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];

并调用方法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]];
}
于 2013-10-26T04:35:08.033 回答
1

在创建标签集标签时,例如:

    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];

并使用以下代码找到它被点击的视图

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

if (tag == 1000) {
...
}
}
于 2013-10-26T12:10:28.517 回答