我是 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"]];
}
}
这是我的错误吗?