开发中遇到这个需求,在网上找到好几种方法,但是遇到坑了,自己做个笔记顺便能帮到有需要的人就好了,
有一种的只有一组的cell那直接把button的tag设置为indexPath.row这个不说,看多组多行的情况
方法一:通过button的坐标点找到在cell上的位置.
CGPoint buttonPosition = [button convertPoint:CGPointZero toView:self.downloadTableVIew];
NSIndexPath *indexPath = [self.downloadTableVIew indexPathForRowAtPoint:buttonPosition];
这个方法需要注意一个问题,就是有可能他计算不出来indepath,打断点buttonPosition有坐标,但是indexPath为nil,这样他不会报错,结果indexPath.section indexPath.row都为0(可能是其他地方没有设置好)要么判断indexPath不为空在进行下一步
方法二:(推荐)通过父控件找到cell在找到indexPath.
NSIndexPath*indexPath=[self.downloadTableVIew indexPathForCell:(UITableViewCell*)[[[button superview]superview]superview]];
可以运行后展开看结构图,根据自己的情况,我使用了三个superView结构是btn--灰色背景View--contentView--cell如果你的btn直接放到cell的contentView上那就是两个,打断点测试下就好了,
方法三:(还未实现)使用自己定义的button,给自定义的btn添加一个indexPath的属性,在创建的时候把cell的indexPath赋值给btn的indexPath,点击后直接取出使用,等我有空整理了在放上来吧,建议使用上面两种足够了