如何知道UITableView中Tableview单元格按钮上的节号?

时间:2013-05-18 05:54:24

标签: iphone ios uitableview

我有一个UITableView,我已经为其创建了一个自定义的UITableViewCell。 tableview中的每一行都有一个按钮。我想知道单击按钮时的节号,以便我知道单击了哪个部分按钮。我已经尝试过在堆栈上找到的一些东西,但没有任何工作。

UIButton *b = sender; 
NSIndexPath *path = [NSIndexPath indexPathForRow:b.tag inSection:0]; 
NSLog(@"Row %d - Section : %d", path.row, path.section);

4 个答案:

答案 0 :(得分:5)

不知道你尝试了什么,但我可能会做这样的事情。在这里从内存中做一些伪代码。

- (void)buttonClicked:(id)sender {
    CGPoint buttonOrigin = [sender frame].origin;
    // this converts the coordinate system of the origin from the button's superview to the table view's coordinate system.
    CGPoint originInTableView = [self.tableView convertPoint:buttonOrigin fromView:[sender superview];

    // gets the row corresponding to the converted point
    NSIndexPath rowIndexPath = [self.tableView indexPathForRowAtPoint:originInTableView];

    NSInteger section = [rowIndexPath section];

}

如果我清楚地思考,如果按钮不直接在UITableView单元格内,这可以提供灵活性。比方说,如果你嵌套在一些中间视图中。

可悲的是,似乎没有iOS等价的NSTableView的rowForView:

答案 1 :(得分:3)

为按钮单击创建处理程序,并将其添加到tableView:cellForRowAtIndexPath:方法

- (void)buttonPressed:(UIButton *)button{

    UITableViewCell *cell = button.superView.superView;

    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    //Now you have indexPath of the cell 
    //do your stuff here

}

答案 2 :(得分:0)

cellForRowAtIndexPath中创建自定义UITableViewCell时,应将其部分作为参数传递给它。它可能看起来像:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

  if (!cell)
  { 
  cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier" section:indexPath.section] autorelease];
  }

    return cell;
 }

现在您的单元格知道它的部分,您可以在MyCustomCell

中执行单击方法时使用它

答案 3 :(得分:0)

试试这个,

首先将部分指定为按钮,然后在cellForRowAtIndexPath方法中添加按钮。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [cell.btnSample setTag:indexPath.section];
    [cell.btnSample addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    ...
}

将Section作为您定义的IBAction发件人的标记( buttonClicked 此处)。

-(IBAction)buttonClicked:(id)sender
{
    NSLog(@"Section: %d",[sender tag]);
}