iPhone - 从自定义单元格中捕捉UIButton触摸事件

iPhone - 从自定义单元格中捕捉UIButton触摸事件

问题描述:

我想构建一个自定义表格视图单元格,并在其中放置一个按钮,当用户单击该按钮以转到某个方法时 - 该方法将知道哪个单元格按钮被按下。iPhone - 从自定义单元格中捕捉UIButton触摸事件

thx

+0

你是从IB创建一个UITableViewCell或programmaticaly? – klefevre 2011-05-23 13:02:10

+0

[检测在UITableView中按下哪个UIButton]的可能重复(http://*.com/questions/1802707/detecting-which-uibutton-was-pressed-in-a-uitableview) – Vladimir 2011-05-23 13:06:34

您可以给按钮一个标签。如果将此标记设置为单元格indexPath.row的数量,则可以始终通过检索标记Value来确定单击了哪个单元格。

按钮标记必须是一个整数btw,但母猪是indexPath.row。

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    Huis *h = [woningen objectAtIndex:indexPath.row]; 
    static NSString *identifier = @"Woning"; 
    WoningTableCell *cell = (WoningTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier]; 
    if (cell == nil) { 
     cell = [[[WoningTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease]; 
    } 
    [cell setNewWoning:h withIndex:indexPath.row]; 
    return cell; 
} 

这里我创建了一个自定义单元格,显示'Huis'的详细信息。当为单元格设置对象时,我还会传递我正在填充的单元格的indexPath.row。

然后在自定义单元格,在设定目标,我还为我的按钮,这样的标签值:

UIButton *indexBtn = [UIButton .... ]; 
indexBtn.tag = indexRowInteger; 

的按钮可能已创建/初始化,在这种情况下,你只设置标签。现在,在功能处理您的ControlEvent资料你可以访问此标签,像这样:

- (void) CellButtonPressed: (id) sender{ 

UIButton *b = ((UIButton *)sender); 
NSInteger tagValue = btn.tag; 

} 

- (void) cellButtonClicked: (id) sender 
{ 
  UIButton *btn = (UIButton *) sender; 
  UITableViewCell *cell = (UITableViewCell *) [[btn superview] superview]; 
  NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
  //do something with indexPath... 
} 

希望这项工作