6

我创建了一个具有自定义 UITableViewCell 的 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);
}

但这也行不通。

谢谢你的协助。

4

2 回答 2

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];
    }
于 2013-05-18T05:35:43.580 回答
1

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

于 2013-05-18T05:35:56.317 回答