Safari网页浏览无法使用URL打开

时间:2013-04-09 10:44:00

标签: iphone ios objective-c xcode cocoa-touch

我是iPhone开发的新手。 我有6个部分的Table视图,每个部分有一行,在4Th部分我添加UILabel。 此UILabel文本是URL(www.google.com)。 我想点击这个标签打开野生动物园,但我不能成功开放野生动物园

我跟着这个UILabel with a hyperlink inside a UITableViewCell should open safari webbrowser?

但它不起作用。

我的代码:

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

这是我的错误?

3 个答案:

答案 0 :(得分:2)

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

你错过了“http://

答案 1 :(得分: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]);

我觉得它可能适合你

答案 2 :(得分:0)

只需添加“http://”即可 例如: -

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