如何知道UITableView中Tableview单元格按钮上的indexPath /行?

时间:2013-05-18 05:29:26

标签: iphone ios uitableview

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

我试过这段代码 - :

-(void)button1Tapped:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);
}

但这也行不通。

感谢您帮助我。

2 个答案:

答案 0 :(得分:20)

试试这个

    - (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] autorelease];
            [[cell contentView] setBackgroundColor:[UIColor clearColor]];
            [[cell backgroundView] setBackgroundColor:[UIColor clearColor]];
             [cell.Mybutton addTarget:self action:@selector(btnCommentClick:) forControlEvents:UIControlEventTouchUpInside];
        }
         cell.Mybutton.tag=indexPath.row;
    }

    -(void)btnCommentClick:(id)sender
    {
            UIButton *senderButton = (UIButton *)sender;  
            NSLog(@"current Row=%d",senderButton.tag);
            NSIndexPath *path = [NSIndexPath indexPathForRow:senderButton.tag inSection:0];
    }

答案 1 :(得分:1)

知道单击tableView哪一行的最佳方法是在使用自定义单元格时在cellForRowAtIndexPath方法中设置单元格按钮的标记值。