0

我是 iPhone 开发的新手。我有 6 个部分的表格视图,每个部分有一行,在第 4 部分我添加了 UILabel。此 UILabel 文本是 URL (www.google.com)。当我单击此标签时,我想打开 safari,但我没有成功打开 safari

我用 UITableViewCell 内的超链接关注这个UILabel 应该打开 safari 网络浏览器吗?

但它不起作用。

我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [Prep defaultBGColor];

        if(indexPath.section == 3)
        {
            self.lblWebsite = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 270, 35)];
            self.lblWebsite.backgroundColor = [UIColor clearColor];
            self.lblWebsite.text= @"www.gmail.com";
            self.lblWebsite.font =[UIFont fontWithName:@"Arial-BoldMT" size:16];
            self.lblWebsite.textAlignment = UITextAlignmentLeft;
            self.lblWebsite.userInteractionEnabled = YES;
            self.lblWebsite.textColor=[UIColor blackColor];
            [cell.contentView addSubview:self.lblWebsite];

            UITapGestureRecognizer *gestureRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openUrl:)];
            gestureRec.numberOfTouchesRequired = 1;
            gestureRec.numberOfTapsRequired = 1;
            [self.lblWebsite addGestureRecognizer:gestureRec];
            [gestureRec release];
       }
    }
  return Cell;
}

方法

- (void)openUrl:(id)sender
{

    UIGestureRecognizer *rec = (UIGestureRecognizer *)sender;

    id hitLabel = [self.view hitTest:[rec locationInView:self.view] withEvent:UIEventTypeTouches];

    if ([hitLabel isKindOfClass:[UILabel class]]) {
         NSLog(@"%@",((UILabel *)hitLabel).text);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"www.google.com"]];
    }
}

这是我的错误吗?

4

3 回答 3

2
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];  

你失踪了“ http://

于 2013-04-09T10:51:23.340 回答
2

你做得对,但我认为之前使用http://www.google.com

NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];

if (![[UIApplication sharedApplication] openURL:url])

NSLog(@"%@%@",@"Failed to open url:",[url description]);

我认为它可能对你有用

于 2013-04-09T10:51:31.240 回答
0

只需添加“http://”即可使用示例:-

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com"]];
于 2013-04-09T11:07:56.957 回答