有时候在画cell的时候,里面的控件我会给它设置tag,用来在cellForRowAtIndexPath中获取每个cell的子控件,如果子控件有个UIButton,你给它设置targeta后,在响应的方法里没办法分是从哪一个cell的button触发的,因为所有的cell的那个UIbutton的tag是一样的。
既然不许改变tag,有没有其他办法知道它的父容器Cell的行数呢?知道行数了不会知道是哪一个cell的Button触发的。
方法1:
NSString* cellStr1 = [NSString stringWithFormat:@"%d", indexPath.row];
[btn_attention setTitle:cellStr1 forState:UIControlEventTouchCancel];
获取title,并转为行数:
NSString* cellIndex = [sender titleForState:UIControlEventTouchCancel];
int tag =[cellIndex intValue];
方法2:
UITableViewCell * cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath * path = [self.baseTableView indexPathForCell:cell];
//获取按钮所在的cell的row
BnetBillMode = [self.tableArray objectAtIndex:path.row];
方法3:
[cell.button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
那么点击button时就会调用
- (void)didTapButton:(UIButton *)sender
剩下的就是如何通过这个sender获得它所在的cell。我们这么实现这个方法,
- (void)didTapButton:(UIButton *)sender
{
CGRect buttonRect = sender.frame;
for (CustomCell *cell in [ self.baseTableView visibleCells])
{
if (CGRectIntersectsRect(buttonRect, cell.frame))
{
//cell就是所要获得的
}
}
}