我通过新建一个nib文件来自定义cell。并在其中添加了一个button,我原本是想通过点击button触发控制器里的方法来显示点击的是第几行的,并在这个方法里添加了如下语句:
-(IBAction)buttonTapped:(id)sender{
UIButton *button = (UIButton *)sender;
UITableViewCell*cell = (UITableViewCell*)[button superview];
NSLog(@" %@",[self.tableView indexPathForCell:cell]);
}
-(IBAction)buttonTapped:(id)sender{
UIButton *button = (UIButton *)sender;
UITableViewCell*cell = (UITableViewCell*)[button superview];
NSLog(@" %@",[self.tableView indexPathForCell:cell]);
}
打印出的语句竟然是null,也就是说没办法得到button所在cell现在所处的indexPath
如果硬要這樣往上挖去找到他的 indexpath 的話, 你必須一層一層往上找,
你會發現, uibutton 的 superview 是 UITableViewCellContentView 而不直接就是你自定義的那個 cell
而後, UITableViewCellContentView 的 superview 的上一層才是你定義的那個 cell
最後, 這個 cell 的上層才是 tableview
你中間跳過了一層, 所以會得到不對的答案.
、、、、、、、、、、、、、、、、、、、、牛牛牛牛牛、、、、、、、、、、、、、、、、、、、、、、、、、、、
其实有一种更简便的方法:在每个button初始化的时候,给每个按钮的tag值设置成行号,这样就可以直接获取到了