UITableView获取cell的indexPath
![此博文包含图片](https://i-blog.csdnimg.cn/blog_migrate/a4c26d1e5885305701be709a3d33442f.gif)
![此博文包含视频](https://i-blog.csdnimg.cn/blog_migrate/a4c26d1e5885305701be709a3d33442f.gif)
假如你是用代码方式直接将控件(如UILabel、UIButton等)加到UITableView的cell中去的话,,,在出了
- -
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath - {
-
//自定义代码 -
return cell; -
}
这个函数后,,,当你点击cell的时候想知道到底是点击了第几行,,这时候你就可以通过在以下代码获得点击的行数。
- UITableViewCell
*cell = (UITableViewCell *)[btn superview]; - NSIndexPath
*indexPath = [_myTableView indexPathForCell:cell]; - NSLog(@"indexPath
is = %i",indexPath.row);
注释:btn是你通过代码的方式添加到cell的一个Button,_myTableView是UITableView的一个关联变量。
假如你是通过新建 .xib的方式新建一个继承UITableViewCell的 .xib(例如:shopCell.xib)文件添加到原有UITableView的cell的方式的话,,,用上面这种方法是获取不到点击cell所在的行数的,也就是说你不知道点击的cell到底是第几行。
同样可以用上面的代码,,不过要稍微修改一下:
- UITableViewCell
*cell = (UITableViewCell *)[[[btn superview] superview] superview]; - NSIndexPath
*indexPath = [_myTableView indexPathForCell:cell]; - NSLog(@"indexPath
is = %i",indexPath.row);
解释:第一句代码中的[btn superview]是shopCell 的contentView,第二个superview是shopCell自己本身的cell,第三个superview是UITableView的cell,,注意不要弄混淆了。
20131024再次编辑:
知道row,然后通过row确定是哪一行的cell
- NSIndexPath
*index1 = [NSIndexPath indexPathForItem:row inSection:0]; - UITableViewCell
*cell1 = [_myTableView cellForRowAtIndexPath:index1];
转自:http://blog.csdn.net/chaoyuan899/article/details/12972131