【问题标题】:How to open a link with a UIButton within a UITableView如何在 UITableView 中打开带有 UIButton 的链接
【发布时间】:2012-07-02 02:51:17
【问题描述】:

我创建了以下代码来显示UITableView 中的按钮。我想为表格中的每个特定单元格添加点击事件,以通过点击该按钮来访问谷歌链接。 如何将点击事件添加到特定单元格的按钮选项中并访问谷歌链接?

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

    static NSString *CellIdentifier = @"cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    UIButton *button =[[UIButton alloc]initWithFrame:CGRectMake(5,5,40,40)];
    [button addTarget:self action:@selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"lori"] forState:UIControlStateNormal];
    [button setTag:9001];
    [cell addSubview:button];
    [cell setIndentationWidth:45];
    [cell setIndentationLevel:1];
    cell.textLabel.text = [thearray objectAtIndex:indexPath.row];

    return cell;
}

-(void) buttonpressed:(UIButton *)sender {}

【问题讨论】:

  • 哇...您的格式有问题。
  • 是的,我知道我没有得到 ..how to put spase between it.but 你能理解吗?
  • 不,它只是不可读。
  • 您的代码似乎有点奇怪。我删除了第二种方法,因为它没有意义。以这种方式,其他人可以理解代码。附:如果您愿意,您可以回滚到之前版本的代码。

标签: ios uitableview hyperlink uibutton


【解决方案1】:

尝试类似:

-(void) buttonpressed:(UIButton *)sender {
    NSString* launchUrl = @"http://apple.com/";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];
}

这将打开指向您传入的 URL 的 safari。

如果你不想打开safari,那么你应该显示你自己的UIWebView

此外,您可能希望将您的按钮添加到contentView

[cell.contentView addSubview:button];

【讨论】:

  • 谢谢!并且您提到的代码仅适用于特定按钮..我想要每个单元格视图代码。如何调用多个按钮
  • 您可以使用与每个按钮相关联的UIButton 标记来了解按下了哪个按钮以及打开哪个 URL。
猜你喜欢
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 2016-08-29
  • 2016-11-12
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
相关资源
最近更新 更多