【问题标题】:Perform action on a button in UITableView对 UITableView 中的按钮执行操作
【发布时间】:2011-10-04 15:14:30
【问题描述】:

我在 UITableViewCell 中有一个 UIButton... 我想对 UIButton 执行一个操作..

我需要将数据发送到为此按钮注册的@selector 方法,以便我可以在用户按下此按钮时执行操作。

如何做到这一点,虽然我发现选择器函数中的(id) sender 参数并不总是在cellForRowAtIndexPath 函数中创建的原始按钮。

cellForRowAtIndexPath 函数内部:

UIImage* pdfImage = [UIImage imageNamed:@"icon_pdf.png"];
UIButton* pdfButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pdfButton setImage:pdfImage forState:UIControlStateNormal];
pdfButton.accessibilityHint = @"path/to/pdf/file";
pdfButton.frame = CGRectMake(0, 0, 40, 40);
[pdfButton addTarget:self action:@selector(openUrlInBrowser:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = pdfButton;

这里是发送者函数:

-(void) openUrlInBrowser:(id)sender
{
    NSLog(@"%@", [sender class]);
    NSString * url=[sender accessibilityHint];
    NSLog(@"%@",url);
    NSLog(@"%@",sender);
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}

【问题讨论】:

  • 你想让那个按钮覆盖整个单元格吗?
  • 查看这些 NSLog 语句的结果会有所帮助。还有你的 cellForRowAtIndexPath 方法的其余部分。

标签: iphone uitableview uibutton


【解决方案1】:

希望我能正确理解这个问题 - 我通常在 uitableview 中添加的按钮上定义一个标签,该标签是该行的索引。在 cellForRowAtIndexPath 中:

[button setTag:indexPath.row];

然后你可以在目标方法中取回它:

- (void) showdatabases:(id) sender {
int row = [[sender valueForKey:@"tag"] intValue];
...

并使用以下方法查询单元格中的值以供您处理:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];

另外,您可以通过访问发送者的超级视图获得相同的结果,但我发现这更难调试。

【讨论】:

    【解决方案2】:

    我更喜欢使用:

    -(void) openUrlInBrowser:(id)sender
    {
      UIButton * button = (UIButton *)sender;
      NSString * url=[button.superview accessibilityHint];
      [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
    }
    

    它不依赖于表格中的单元格位置

    【讨论】:

    • 你的代码没问题,很清楚!我添加了其他解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多