UITableView indexPath.row 问题 [英] UITableView indexPath.row issue

查看:28
本文介绍了UITableView indexPath.row 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 tableView,它加载一个自定义的 UITableViewCell,里面有一个点击"按钮.当用户点击按钮时调用一个方法.

I am using a tableView which loads a custom UITableViewCell with a "Tap" button inside it. A method is called when user clicks the button.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{...
    [btnRowTap addTarget:self action:@selector(didButtonTouchUpInside:) forControlEvents:UIControlEventTouchDown];
 ...
return cell;
}

在 didButtonTouchUpInside 方法中,我尝试通过以下方式检索所选行的值:

In the didButtonTouchUpInside method, Im trying to retrieve the value of row selected in the following way:

-(IBAction)didButtonTouchUpInside:(id)sender{
UIButton *btn = (UIButton *) sender;
UITableViewCell *cell = (UITableViewCell *)btn.superview;
NSIndexPath *indexPath = [matchingCustTable indexPathForCell:cell];
NSLog(@"%d",indexPath.row);
}

问题是,在任何行单击按钮时,我每次都得到相同的 0 值.我哪里出错了?

The problem is that on clicking button at any row, I am getting the same value of 0 every time. Where am I going wrong?

推荐答案

您必须不要依赖 UITableViewCell 的视图层次结构.这种方法在 iOS7 中会失败,因为 iOS7 更改了单元格的视图层次结构.你的按钮和 UITableViewCell 之间会有一个额外的视图.

You must NOT rely on the view hierarchy of a UITableViewCell. This approach will fail in iOS7, because iOS7 changes the view hierarchy of the cell. There will be an additional view between your button and the UITableViewCell.

有更好的方法来处理这个问题.

There are better ways to handle this.

  1. 转换按钮框架使其相对于tableview
  2. 向 tableView 询问新框架原点处的 indexPath

.

-(IBAction)didButtonTouchUpInside:(id)sender{
    UIButton *btn = (UIButton *) sender;
    CGRect buttonFrameInTableView = [btn convertRect:btn.bounds toView:matchingCustTable];
    NSIndexPath *indexPath = [matchingCustTable indexPathForRowAtPoint:buttonFrameInTableView.origin];

    NSLog(@"%d",indexPath.row);
}

这篇关于UITableView indexPath.row 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆