【问题标题】:How to know the indexPath/row on button click of Tableview cell in a UITableView? [duplicate]如何知道 UITableView 中的 Tableview 单元格按钮单击时的 indexPath/row? [复制]
【发布时间】:2013-05-13 07:54:21
【问题描述】:

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

但这也行不通。

感谢您帮助我。

【问题讨论】:

  • 使用标签是错误的做法。

标签: iphone ios uitableview


【解决方案1】:

试试这个

    - (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];
    }

【讨论】:

  • 效果很好!谢谢!
  • 这在嵌套表的情况下不起作用。当我们有多个会话时。
  • @SAMIRRATHOD 先生,如果我在一个视图中有多个表视图,那么如何知道 senderButton.tag 从哪个表返回?
  • @knocker,对于多个部分的情况,使用具有属性 NSIndexPath *indexPath 的自定义单元格会有所帮助,但请注意,应确保每个自定义单元格的 indexPath 值始终是最新的。对于多个tableview,给每个tableview一个tag,然后分别传给每个cell,只是一个想法,还没试过。
【解决方案2】:

在使用自定义单元格时,通过在 cellForRowAtIndexPath 方法中设置单元格按钮的标签值来了解点击哪一行的 tableView 的最佳方法。

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 2017-12-29
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2015-01-30
    相关资源
    最近更新 更多